I have the following code:
<?php
$items = simplexml_load_file("http://foo.xml");
foreach ($items->bar->baz as $item) {
echo $item;
}
?>
I want to cache the xml file, so I was told开发者_开发技巧 to use:
$cacheName = "foo.xml.cache";
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 24 * 60 * 60; // one day
if (!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds)
{
$contents = file_get_contents("http://foo.xml");
file_put_contents($cacheName, $contents);
}
$dom = simplexml_load_file($cacheName);
I tried creating a function called to call right before the foreach loop. How can I do this? Thank you!
I think this expression is backwards:
filemtime($cacheName) > time() + $ageInSeconds
I think it should be
filemtime($cacheName) + $ageInSeconds < time()
or, equivalently:
filemtime($cacheName) < time() - $ageInSeconds
精彩评论