2010-06-21 65 views
0

我在我的网站有一个雅虎货币脚本,但他们花费太多时间来加载并且正在减慢我的网站。我如何缓存它们并每3600分钟刷新一次缓存?如何实现雅虎货币缓存?

回答

2

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

+0

我怎么可以使用此功能的PHP? – 2010-06-21 06:57:56

0

而且,而非fgets其由线而慢读文件行,因为你没有操纵线,你应该考虑使用file_get_contents函数。

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