PHP,SimpleXML对象的json_encode,json_decode [英] PHP, json_encode, json_decode of SimpleXML Object

查看:114
本文介绍了PHP,SimpleXML对象的json_encode,json_decode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中的一个函数执行以下操作:

A function in my application does the following:

  • 使用史努比捕获网页
  • 将结果加载到DOMDocument
  • 将DOMDocument加载到简单XML对象中
  • 运行XPath隔离所需的文档部分
  • json_encode结果并保存到数据库以供以后使用.

当从数据库中恢复此块并对其进行解码时,出现了我的问题. var_dump对象时,我可以看到@attributes,但是找不到允许我访问它们的命令组合.

My problem arises when recovering this block from the database, and decoding it. I can see the @attributes when I var_dump the object, but cannot find a combination of commands that allows me to access them.

错误消息是:致命错误:不能将stdClass类型的对象用作数组

Error message is: Fatal error: Cannot use object of type stdClass as array

下面是我的对象的一个​​示例.除其他方法外,我还尝试过.

Below is a sample of my object. I have tried, amongst other what used to work.

echo $obj['class'];

stdClass Object
(
    [@attributes] => stdClass Object
        (
            [class] => race_idx_hdr
        )

    [img] => stdClass Object
        (
            [@attributes] => stdClass Object
                (
                    [src] => /Images/Icons/i_blue_bullet.gif
                    [alt] => image
                    [title] => United Kingdom
                )

        )

    [a] => Fast Cards
)

推荐答案

从数据库中解码json时,您将获得类型为'stdClass'的对象,而不是SimpleXMLElement :: xpath返回的原始类型'SimpleXMLElement'的对象功能.

When you decode the json from the database, you get an object of type 'stdClass' instead of the original type 'SimpleXMLElement' returned by the SimpleXMLElement::xpath function.

stdClass对象不了解SimpleXMLElement对象用于允许访问属性的伪数组语法.

The stdClass object does not 'know' about the pseudo array syntax used by SimpleXMLElement objects to allow accessing the attributes.

通常,您将使用serialize()和unserialize()函数而不是json_encode/decode将对象存储在数据库中,但是不幸的是,SimpleXMLElements不适用于这些对象.

Normally you would use the serialize() and unserialize() functions instead of json_encode/decode to store objects in a database, but unfortunately, SimpleXMLElements are not working with those.

作为一种选择,为什么不存储实际的xml并在从数据库中获取它之后将其读回SimpleXML:

As an alternative, why not just store the actual xml and read it back to SimpleXML after fetching it from the database:

// convert SimpleXMLElement back to plain xml string
$xml = $simpleXML->asXML();

// ... code to store $xml in the database
// ... code to retrieve $xml from database

// recreate SimpleXMLELement
$simpleXML = simplexml_load_string($xml);

这篇关于PHP,SimpleXML对象的json_encode,json_decode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆