【问题标题】:How to cache XML file in PHP?如何在 PHP 中缓存 XML 文件?
【发布时间】:2011-10-17 22:44:19
【问题描述】:

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

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

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

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

谢谢!

【问题讨论】:

    标签: php xml caching


    【解决方案1】:

    一个非常简单的缓存是将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);
    // ...
    

    注意:这当然假设文件已成功生成,远程文件已成功下载等几件事。

    【讨论】:

    • 如果页面由使用不同计算机的两个不同用户访问会发生什么?和不同的参数?
    • 不要忘记 clearstatcache()filemtime() 函数。
    • 为什么不time() - filemtime($cacheName) >= $ageInSeconds
    • 只是一个评论,多年后 - 正如答案中所述,缓存永远不会触发,因为时间比较是向后的。您需要使用上面评论中的时间比较。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2013-03-21
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多