【问题标题】:Node no longer exists using SimpleXML使用 SimpleXML 的节点不再存在
【发布时间】:2011-07-12 23:14:51
【问题描述】:

尝试使用名为 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;
}

【问题讨论】:

标签: php simplexml


【解决方案1】:

您的$response_xmlSimpleXMLElement 类的一个实例。 SimpleXMLElement 不应(取消)序列化,因为它在对象中包装了 resource

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

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

【讨论】:

    【解决方案2】:

    您不应该(不能?)serializeunserialize SimpleXML 对象。它是 XML,它是一种序列化格式。这不是《盗梦空间》!

    调用asXML 方法来获取实际的XML,然后将其存储起来。

    【讨论】:

    • 那么为什么可以序列化 DomDocument?
    • @Gildas,尝试序列化您的 DOMDocument,甚至是 DOMNodeList。您会发现虽然它们序列化 没有错误,但它们完全是空的。同样,XML 一种序列化格式。
    猜你喜欢
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多