开发者

How to create PHP cache function?

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜