使用 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
$response_xml
是SimpleXMLElement
类的实例。SimpleXMLElement
不应被(取消)序列化,因为它在其中包装了 资源物体。相反,序列化一些能够在整个过程中幸存下来的东西;来自提要的原始响应、将 XML 加载到
SimpleXMLElement
并使用asXML()
方法、您想要的(可能是字符串)值的数组,或其他可以序列化的结构。需要考虑的一件事是,您将在“较旧”(宽松地使用该术语)版本的 PHP 中看到
unserialize(): Node no moreexists
警告。从 PHP 5.3.2 开始,行为更改为抛出Exception
,并显示消息不允许“SimpleXMLElement”序列化
。Your
$response_xml
is an instance of theSimpleXMLElement
class. ASimpleXMLElement
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 theasXML()
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 anException
with the messageSerialization of 'SimpleXMLElement' is not allowed
.您不应该(不能?)
序列化
和反序列化
SimpleXML 对象。它是 XML,它首先是一种序列化格式。这里不是盗梦空间!调用
asXML
方法获取实际的XML,然后存储它。You shouldn't (can't?)
serialize
andunserialize
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.