![](/img/trans.png)
[英]What is the proper way to parse yahoo currency http://finance.yahoo.com/connection/currency-converter-cache?date?
[英]How to implement a Yahoo currency cache?
我的網站上有Yahoo貨幣腳本,但是它們花費了太多時間來加載,並降低了我的網站速度。 如何緩存它們並每3600分鍾刷新一次緩存?
您需要一些地方來存儲這些結果。 MySQL是一個流行的選擇,但是如果數據不需要保留或具有歷史值,則使用內存緩存會更容易。 根據您的主機,這兩個選項可能都可用。
這個想法是:
這樣的事情應該可以解決問題:
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;
}
}
另外,與其使用fgets
逐行讀取文件,還不如使用fgets
,而且由於您沒有在操縱一行,所以應該考慮使用file_get_contents
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.