使用SimpleXML不再存在节点

时间:2011-03-10 18:52:32

标签: php simplexml

尝试使用名为get_transient的wordpress函数构建来缓存xml文件,但我收到了一个php错误:

unserialize()[function.unserialize]:节点不再存在

//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;
}

2 个答案:

答案 0 :(得分:5)

您的$response_xmlSimpleXMLElement类的实例。 SimpleXMLElement不应该(未)序列化,因为它会在对象中包含resource

相反,序列化一些能够在这个过程中幸存下来的东西;来自feed的原始响应,将所有/部分XML加载到SimpleXMLElement并使用asXML()方法,您想要的(可能是字符串)值的数组,或其他一些结构可以序列化。

要考虑的一件事是,您将在“较旧”(使用松散术语)版本的PHP中看到 unserialize(): Node no longer exists 警告。自PHP 5.3.2起,行为更改为抛出Exception消息 Serialization of 'SimpleXMLElement' is not allowed

答案 1 :(得分:3)

你不应该(不能?)serializeunserialize SimpleXML对象。它是XML,它是一种序列化格式。这不是Inception!

调用asXML方法获取实际的XML,然后存储它。

相关问题