从远程站点获取数据并进行缓存?

时间:2014-11-03 19:53:01

标签: php caching

我从XML页面获取一些数据以进行一些货币计算。 像这样:$rates = file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

然后我在函数中使用该数据。如果我在每个页面上包含执行货币转换的功能(例如,通过include("../lib/functions.php")),那是否意味着每个页面加载都会重新获取数据?我可以对远程站点进行一些巧妙的缓存吗?

1 个答案:

答案 0 :(得分:1)

它会在每个页面加载时获取该文件,是的,您应该缓存您正在获取的文件。

缓存此文件并加载它的基本方法是创建缓存版本,如果尚未加载则加载该文件。

$newCacheFile = 'eurofxref-daily.xml.cache'; //New file

if (!file_exists($cacheName)) { //Check For File
    $newCacheContent= file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'); //Get This File
    file_put_contents($newCacheFile, $newCacheContent); //Put the contents of external to new
}

$loadedFile = simplexml_load_file($newCacheFile); //Load the new file

您必须检查文件是否成功创建等,但这样做不应该太难:)


如果你想获得该文件的新版本,比如每24小时一次,那么就可以将这个小方法添加到if语句filemtime()中,这样我们就可以检查文件的大小。您的代码将如下所示:

$newCacheFile = 'eurofxref-daily.xml.cache'; //New file
$checkCacheFilePeriod = 86400; //24 hours in seconds

if (!file_exists($cacheName) || filemtime($newCacheFile) > time() + $checkCacheFilePeriod ) { //Check For File and the date it was last edited.
    $newCacheContent= file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'); //Get This File
    file_put_contents($newCacheFile, $newCacheContent); //Put the contents of external to new
}

$loadedFile = simplexml_load_file($newCacheFile); //Load the new file

以下是我刚刚遇到的一篇文章,它可能是缓存创建文件的更好方法:http://www.catswhocode.com/blog/how-to-create-a-simple-and-efficient-php-cache

相关问题