Main Content

Caching an XML feed

Archive - Originally posted on "The Horse's Mouth" - 2005-08-26 18:39:20 - Graham Ellis

If you're using PHP to add a newsfeed to your site, please be kind to the news feed supplier and cache the feed if your page is a popular one. I posted a couple of weeks ago ... a link to a piece of code that grabs a news feed .... and I've enhanced it now to do the caching. Here's the modified code:

$feed = "http://thescotsman.scotsman.com/uk.cfm?format=rss";
$copy = 1;
if (time() - @filemtime("haggis.xml") < 120) {
$feed = "haggis.xml";
$copy = 0;
}

$fh = fopen($feed,"r");
if ($copy) $saver = fopen("haggis.xml","w");
while ($xmlcontent = fread($fh,1024)) {
if ($copy) fputs($saver,$xmlcontent);
xml_parse($parser,$xmlcontent,feof($fh));
}

Links ...
Previous posting
Original full source code listing
Running Script