2010-06-21 61 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; 
    } 
}