【发布时间】: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"] 阅读id 和title 时会出错:
致命错误:未捕获的错误:不能使用 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。