如何实现Yahoo货币缓存?

时间:2010-06-21 06:28:37

标签: php

我的网站上有一个Yahoo货币脚本,但是他们花费了太多时间来加载并减慢我的网站速度。如何每隔3600分钟缓存它们并刷新缓存?

3 个答案:

答案 0 :(得分:2)

您需要一些地方来存储这些结果。 MySQL是一种流行的选择,但如果数据不需要保留或具有历史价值,那么使用memcache会更容易。根据您的主机,这两个选项都可以使用。

答案 1 :(得分:2)

这个想法是:

  • 创建某种缓存目录并设置定义的缓存期限
  • 然后,在函数的最开始,检查缓存
    • 如果存在,请检查它的年龄。
      • 如果在范围内,请将其
    • 如果缓存太旧了
      • 使用实时数据并将该数据设置为缓存文件。

这样的事情可以解决问题:

define(CACHE_DIR, 'E:/xampp/xampp/htdocs/tmp');
define(CACHE_AGE, 3600);
/**
 * Adds data to the cache, if the cache key doesn't aleady exist.
 * @param string $path the path to cache file (not dir)
 * @return false if there is no cache file or the cache file is older that CACHE_AGE. It return cache data if file exists and within CACHE_AGE 
 */
function get_cache_value($path){
    if(file_exists($path)){
        $now = time();
        $file_age = filemtime($path);
        if(($now - $file_age) < CACHE_AGE){
            return file_get_contents($path);
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function set_cache_value($path, $value){
    return file_put_contents($path, $value);
}

function kv_euro () {
    $path = CACHE_DIR . '/euro.txt';

    $kveuro = get_cache_value($path);
    if(false !== $kveuro){
        echo "\nFROM CACHE\n";
        return round($kveuro, 2);
    } else {
        echo "\nFROM LIVE\n";
        $from   = 'EUR'; /*change it to your required currencies */
        $to     = 'ALL';
        $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
        $handle = @fopen($url, 'r');

        if ($handle) {
            $result = fgets($handle, 4096);
            fclose($handle);
        }
        $allData = explode(',',$result); /* Get all the contents to an array */
        $kveuro = $allData[1];
        set_cache_value($path, $kveuro);
        return $kveuro;
    }
}

答案 2 :(得分:0)

此外,您应该考虑使用 file_get_contents 功能,而不是fgets逐行读取文件,而不是操纵一行,而应该考虑使用 {{3}} 功能。

相关问题