Consider the following function prototype for caching object from cached RSS(XML) feed:
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));
}
The function calls are as follows:
$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);}
I get the following error:
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))
Any help making this program to work is greatly appreciated.
Probably, the SimpleXMLElement class, like many built-in PHP objects, cannot be serialized.
Instead, you could call the class method asXML (which returns a valid XML string if you pass no parameters) and serialize this. You can then recreate the SimpleXMLElement class by calling simplexml_load_string() on this string.