我使用这个脚本来检索谷歌网页字体列表。我如何缓存结果并使用它来确定是从缓存还是服务器调用加载?
$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'];
}
您可以创建一个序列化数据的本地副本,并且每小时只更新一次文件:
$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);
}
我想你会想要做一个服务器调用每当谷歌网页字体文件的变化。这在一个脚本中是不可能的。理想情况下,您应该有另一个脚本,仅查询和缓存字体列表,并且您在这里列出的代码将始终使用缓存的值。