MagpieRSS is a XML-based RSS parser in PHP. MagpieRSS supports most RSS versions including modules and namespaces. Magpie RSS also supports caching which is kind a must while parsing any feed because you don’t want to fetch the feed for every hit on your website and risk getting banned.
Although Magpie RSS is really useful and I’ve used it in many projects, one of the feature which is missing from Magpie is setting different cache ages. I had to setup few feeds in a website recently and set different caching age for different feeds. If you are facing similar problem, read on to check the solution.
I made few following changes in the code of function function fetch_rss inside ‘rss_fetch.php’ file.
/*added 2nd parameter for setting different cache age and set existing MAGPIE_CACHE_AGE as default */
function fetch_rss ($url, $magpie_cache_age=MAGPIE_CACHE_AGE) {
// initialize constants
init();
if ( !isset($url) ) {
error("fetch_rss called without a url");
return false;
}
// if cache is disabled
if ( !MAGPIE_CACHE_ON ) {
// fetch file, and parse it
$resp = _fetch_remote_file( $url );
if ( is_success( $resp->status ) ) {
return _response_to_rss( $resp );
}
else {
error("Failed to fetch $url and cache is off");
return false;
}
}
// else cache is ON
else {
// Flow
// 1. check cache
// 2. if there is a hit, make sure its fresh
// 3. if cached obj fails freshness check, fetch remote
// 4. if remote fails, return stale object, or error
//we are not using constant MAGPIE_CACHE_AGE rather using parameter age **added by parorrey**
$cache = new RSSCache( MAGPIE_CACHE_DIR, $magpie_cache_age );
And that was it. Now you can call the function fetch_rss with the cache age different than the default MagpisRSS cache age defined in constant MAGPIE_CACHE_AGE.
$rss = fetch_rss( $url , 3600 * 12 ); //3600 * 12 means 12 hours
You can call the function with one (default) parameter and it’ll still work just fine albeit caching the feed to default cache age.
$rss = fetch_rss( $url ); //default cache age
Hopefully it’ll help someone setting different cache ages for different RSS feeds in MagpieRSS.