如何在PHP中缓存XML文件? [英] How to cache XML file in PHP?

查看:78
本文介绍了如何在PHP中缓存XML文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

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

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...

谢谢!

推荐答案

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

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.

这篇关于如何在PHP中缓存XML文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆