2011-12-17 42 views
0

我正在使用此腳本來檢索Google Web字體列表。如何緩存結果並使用它來確定是否從緩存或服務器調用進行加載?如何在調用新數據之前緩存服務器調用並測試緩存過期?

$googleFontsArray = array(); 
$googleFontsArrayContents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php'); 
$googleFontsArrayContentsArr = unserialize($googleFontsArrayContents); 

foreach($googleFontsArrayContentsArr as $font) 
{ 
    $googleFontsArray[$font['font-name']] = $font['font-name']; 
} 

回答

2

你可以做的序列化數據的本地副本,並只更新文件每隔一小時:

$cache_file = 'font_cache'; 

$update_cache = false; 
$source = $cache_file; 
if(!file_exists($cache_file) || time() - filemtime($cache_file) >= 3600) // Cache for an hour 
{ 
    $source = 'http://phat-reaction.com/googlefonts.php?format=php'; 
    $update_cache = true; 
} 

$googleFontsArray = array(); 
$googleFontsArrayContents = file_get_contents($source); 
$googleFontsArrayContentsArr = unserialize($googleFontsArrayContents); 

foreach($googleFontsArrayContentsArr as $font) 
{ 
    $googleFontsArray[$font['font-name']] = $font['font-name']; 
} 

if($update_cache) 
{ 
    file_put_contents($cache_file, $googleFontsArrayContents); 
} 
+0

+1作品很有魅力! – RegEdit 2011-12-17 20:09:00

0

我假設你想在Google網絡字體文件發生變化時進行服務器調用。這在一個腳本中是不可能的。理想情況下,您將擁有另一個只查詢和緩存字體列表的腳本,並且您在此處列出的代碼將始終使用緩存的值。

+0

感謝朱利安,Tim的例子確實很好。 – RegEdit 2011-12-17 20:09:42