【问题标题】:How extract @attributes from stdClass Object? [duplicate]如何从 stdClass 对象中提取@attributes? [复制]
【发布时间】:2021-07-04 10:45:54
【问题描述】:

如何从 stdClass 对象中提取属性?我有变量$data。对它执行print_r 我得到:

stdClass Object
(
    [@attributes] => stdClass Object
        (
            [id] => cover
            [title] => Cover
        )

    [text] => text
)

当我尝试阅读 text 时没问题。但是当我尝试使用$data["id"]$data["title"] 阅读idtitle 时会出错:

致命错误:未捕获的错误:不能使用 stdClass 类型的对象作为数组...

我该如何解决?唯一的机会是使用json_encode/json_decode 进行数组转换?没有更面向对象的解决方案吗?

谢谢。

【问题讨论】:

  • 这能回答你的问题吗? How do I extract data from JSON with PHP?
  • 搜索该错误会发现您不是在处理数组。上面的链接解释了如何获取数组而不是对象。
  • 您在阅读 XML 吗?如果是这样,请查看 SimpleXML 以提供帮助。
  • 这看起来很可疑,就像您已将 XML 转换为 SimpleXML 对象,然后将其转换为 JSON,然后将其转换回一个用处不大的对象。如果是这样,不要。请改为阅读the usage examples for SimpleXML in the manual

标签: php stdclass


【解决方案1】:

通常,您只需像这样使用属性的名称:

$data->foo

但是,由于您的属性名称@attributes 包含一个特殊字符,您必须使用此扩展语法:

$data->{'@attributes'}

然后,您可以进一步引用它的子键:

$id = $data->{'@attributes'}->id;

或者,你可以传递一个真实值作为 json_decode() 的第二个参数,然后你会得到一个数组而不是一个对象:

$data = json_decode($raw, true);
$id = $data['@attributes']['id'];

【讨论】:

  • 谢谢,不知道这个sintax。
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 2020-06-04
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多