繁体   English   中英

PHP,json_encode,SimpleXML Object的json_decode

[英]PHP, json_encode, json_decode of SimpleXML Object

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

  • 使用Snoopy捕获网页
  • 将结果加载到DOMDocument中
  • 将DOMDocument加载到Simple XML Object中
  • 运行XPath以隔离所需的文档部分
  • json_encode结果并保存到数据库供以后使用。

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

错误消息是:致命错误:无法使用stdClass类型的对象作为数组

下面是我的对象示例。 我曾尝试过,其中包括以前的工作。

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
)

我实际上并不真正理解你想要做什么以及抛出错误的地方,但是要访问你可以使用的对象的属性

echo $obj->{'@attributes'}->class; // prints "race_idx_hdr"
echo $obj->img->{'@attributes'}->src; // prints "/Images/Icons/i_blue_bullet.gif"
echo $obj->img->{'@attributes'}->alt; // prints "image"
echo $obj->img->{'@attributes'}->title; // prints "United Kingdom"
echo $obj->a; // prints "Fast Cards"

这种奇怪的语法( $obj->{'@attributes'} )是必需的,因为@ -symbol在PHP中保留,不能用于标识符。

从数据库解码json时,会得到一个类型为'stdClass'的对象,而不是SimpleXMLElement :: xpath函数返回的原始类型'SimpleXMLElement'。

stdClass对象不“知道”SimpleXMLElement对象用于允许访问属性的伪数组语法。

通常你会使用serialize()和unserialize()函数而不是json_encode / decode来存储数据库中的对象,但不幸的是,SimpleXMLElements不能使用它们。

作为替代方案,为什么不只是存储实际的xml并在从数据库中获取后将其读回SimpleXML:

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

如果将对象转换为数组,则结果是一个数组,其元素是对象的属性。

$asArray = (array)$myObj;
echo $asArray['@attribute'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM