考慮下面的函數原型爲緩存對象從緩存RSS(XML)飼料:PHP的SimpleXML對象緩存
function cacheObject($xml,$name,$age = 3600)
{
// directory in which to store cached files
$cacheDir = "cache/";
// cache filename
$filename = $cacheDir.$name;
// default to fetch the file
$cache = true;
// but if the file exists, don't fetch if it is recent enough
if (file_exists($filename))
{
$cache = (filemtime($filename) < (time()-$age));
}
// fetch the file if required
if ($cache)
{
$item = $xml->channel->item;
file_put_contents($filename,serialize($item));
// update timestamp to now
touch($filename);
}
// return the cache filename
return unserialize(file_get_contents($filename));
}
函數調用如下:
$urlD = "http://somerss.php";
$xmlD = simplexml_load_file(cacheFetch($urlD,'cachedfeedD.xml',3600));
$itemD = '';
if($xmlD === FALSE)
{$itemD = '';}
else
{$itemD = cacheObject($xmlD,'cacheobjectD',3600);}
$urlM = "somerss2.php";
$xmlM = simplexml_load_file(cacheFetch($urlM,'cachedfeedM.xml',3600));
$itemM = '';
if($xmlM === FALSE)
{$itemM = '';}
else
{$itemM = cacheObject($xmlM,'cacheobjectM',3600);}
我得到以下錯誤:
Fatal error: Uncaught exception 'Exception'
with message 'Serialization of 'SimpleXMLElement' is not allowed' in C:\xampp\htdocs\sitefinal\cacheObject.php:20 Stack trace: #0 C:\xampp\htdocs\sitefinal\cacheObject.php(20): serialize(Object(SimpleXMLElement))
任何幫助使這個程序的工作非常感謝。
您可以舉一些這種情況下的程序代碼示例,請 – George
如果該對象無法序列化,您實際上只能緩存該提要的響應。我爭論的是改變這個問題。 –