3

I am obtaining an XML file from a remote server which contains fairly static data. Here is my code:

$dom = simplexml_load_file("foo.xml");

foreach ($dom->bar->baz as $item) {
echo $item;
}

Since the data is rarely changing, there is no need to ping the server on each page load...How can I cache foo.xml in a simple manner? Keep in mind that I am a beginner...

Thank you!

dmubu
  • 33
  • 1
  • 3

1 Answers1

10

A very simplistic cache would be to store the xml file into a directory, and updated every hour or so

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.something.com/foo.xml');
  file_put_contents($cacheName, $contents);
}

$dom = simplexml_load_file($cacheName);
// ...

note: This of course assumes several things like the file was successfully generated, the remote file successfully downloaded, etc.

Ben Rowe
  • 28,406
  • 6
  • 55
  • 75
  • what happen if the page is access by two different users with different computers? and with diffrent parameters? – Harish Kumar Sep 25 '12 at 08:54
  • Don't forget `clearstatcache()` with the `filemtime()` function. – Volomike Jan 13 '15 at 06:05
  • Why not `time() - filemtime($cacheName) >= $ageInSeconds`? – l2aelba Dec 14 '15 at 13:34
  • Just a comment, many years later -- as stated in the answer, the cache will never trigger, because the time comparison is backwards. You need to use the time comparison in the comment just above. – FoulFoot Jun 08 '20 at 00:56