缓存PHP中的天气


Cache Weather in PHP

我的代码:

<? 
    $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(),这是我应该使用的吗?

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

若要正确执行此操作,请将生成的 xml 从文件中写入。每次脚本运行时,您都会检查该文件的上次更新时间。如果是 5>小时,您可以获取/保存新副本。

例如

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