如何在PHP中缓存XML文件


How to cache XML file in PHP?

我正在从包含相当静态数据的远程服务器获取XML文件。下面是我的代码:

$dom = simplexml_load_file("foo.xml");
foreach ($dom->bar->baz as $item) {
echo $item;
}

由于数据很少更改,因此不需要在每次加载页面时ping服务器…如何以简单的方式缓存foo.xml ?请记住,我是一个初学者……

谢谢!

一个非常简单的缓存是将xml文件存储到一个目录中,并每小时更新一次

$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);
// ...

注意:这当然假设了一些事情,如文件成功生成,远程文件成功下载,等等。