Trying to cache an xml file using the build in wordpress function called get_transient but I'm getting a php error:
unserialize() [function.unserialize]: Node no longer exists
//check the db to see if it exists ( get_transient is a WordPress function)
if (false === ($response_xml = get_transient('stats_from_xml_feed'))){
$request_url = "http://example.com/feed.xml";
$request_url = urlencode($request_url);
$response_xml = @simplexml_load_file($request_url);
//kill request if connection problem
if ($response_xml === FALSE){
exit ('could not connect');
} else {
// here we throw it into the WordPress temp DB using set_transient for 12 hours
set_transient('stats_from_xml_feed', $response_xml, 60*60*12);
//some output
$res = $response_xml;
$name = $res->name;
echo $name;
}
Your $response_xml
is an instance of the SimpleXMLElement
class. A SimpleXMLElement
should not be (un)serialized, because it wraps a resource within the object.
Instead, serialize something which will happily survive the process; the raw response from the feed, all/part of the XML after loading it into the SimpleXMLElement
and using the asXML()
method, an array of the (likely string) values you want, or some other structure which is okay to be serialized.
One thing to consider is that you will see the unserialize(): Node no longer exists
warning in "older" (to use the term loosely) versions of PHP. As of PHP 5.3.2, the behaviour changed to throw an Exception
with the message Serialization of 'SimpleXMLElement' is not allowed
.
You shouldn't (can't?) serialize
and unserialize
the SimpleXML object. It's XML, which is a serialization format to begin with. This ain't Inception here!
Call the asXML
method to get the actual XML, then store that instead.