用PHP缓存天气

时间:2012-08-13 02:43:29

标签: php xml xml-parsing

我的代码:

<? 
    $url = 'http://w1.weather.gov/xml/current_obs/KGJT.xml'; 
    $xml = simplexml_load_file($url); 
?>

<? 
    echo $xml->weather, " ";
    echo $xml->temperature_string;
?>

这很好用,但我读到缓存外部数据是页面速度的必要条件。我怎么能缓存这个让我们说5个小时呢?

我调查了ob_start(),这是我应该使用的吗?

2 个答案:

答案 0 :(得分:1)

ob_start不是一个好的解决方案。这仅适用于需要修改或刷新输出缓冲区的情况。您的XML返回数据未发送到缓冲区,因此不需要这些调用。

这是我过去使用的一种解决方案。不需要MySQL或任何数据库,因为数据存储在平面文件中。

$last_cache = -1;
$last_cache = @filemtime( 'weather_cache.txt' ); // Get last modified date stamp of file
if ($last_cache == -1){ // If date stamp unattainable, set to the future
    $since_last_cache = time() * 9;
} else $since_last_cache = time() - $last_cache; // Measure seconds since cache last set

if ( $since_last_cache >= ( 3600 * 5) ){ // If it's been 5 hours or more since we last cached...

    $url = 'http://w1.weather.gov/xml/current_obs/KGJT.xml'; // Pull in the weather
    $xml = simplexml_load_file($url); 

        $weather = $xml->weather . " " . $xml->temperature_string;

    $fp = fopen( 'weather_cache.txt', 'a+' ); // Write weather data to cache file
    if ($fp){
        if (flock($fp, LOCK_EX)) {
           ftruncate($fp, 0);
           fwrite($fp, "\r\n" . $weather );
           flock($fp, LOCK_UN);
        }
        fclose($fp);
    }
}

include_once('weather_cache.txt'); // Include the weather data cache

答案 1 :(得分:1)

ob系统用于脚本内缓存。它对持久性多调用缓存没有用。

要正确执行此操作,您需要从文件中编写生成的xml。每次脚本运行时,您都要检查该文件的最后更新时间。如果它是&gt; 5个小时,你获取/保存一份新的副本。

e.g。

$file = 'weather.xml';
if (filemtime($file) < (time() - 5*60*60)) {
    $xml = file_get_contents('http://w1.weather.gov/xml/current_obs/KGJT.xml');
    file_put_contents($file, $xml);
}
$xml = simplexml_load_file($file); 

echo $xml->weather, " ";
echo $xml->temperature_string;
相关问题