3/15/2006
Caching Remote RSS Feeds With PHP
Previously I noted how Wordpress' admin main page took forever to load because of the remote RSS feeds it checks on every page load. After wading through the code I found that the Magpie RSS parser Wordpress uses does have a caching system built in but it doesn't appear to be enabled. The Wordpress Trac system contains a ticket saying this should be included in WP 2.1.
I wrote a snippet that can be integrated into any remote fetching system to cache the resultant fetched data transparently.
$fetch = true;
$cache_file = './.news_rss';
if(file_exists($cache_file)) {
$mtime = filemtime($cache_file);
// if file is older than 2hrs refetch
if($mtime > (T_STAMP - 7200)) $fetch = false;
}
if($fetch) {
// fetch the remote file
$url = 'http://domain.com/rss.php';
$fp = fopen($url, "r");
if(! $fp) return false;
while (! feof($fp)) {
$str .= fread($fp, 80);
}
fclose($fp);
// cache result
$fp = fopen($cache_file, 'w');
fwrite($fp, $str, strlen($str));
} else {
// read from the cached file
$fp = fopen($cache_file, "r");
if(! $fp) return false;
while (! feof($fp)) {
$str .= fread($fp, 80);
}
fclose($fp);
}
?>
Popularity: 10%


