4

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

  • 使用 Snoopy 捕获网页
  • 将结果加载到 DOMDocument
  • 将 DOMDocument 加载到简单的 XML 对象中
  • 运行 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
)
4

3 回答 3

3

我实际上并不真正了解您要做什么以及引发错误的位置,但是要访问您可以使用的对象的属性

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 中是保留的,不能用于标识符。

于 2009-10-01T17:10:50.763 回答
2

当您从数据库中解码 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);
于 2009-10-01T17:24:46.600 回答
0

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

$asArray = (array)$myObj;
echo $asArray['@attribute'];
于 2009-10-01T17:10:03.727 回答