如何在 PHP 中访问以 @ 开头的 stdClass 成员

发布于 2024-10-11 14:52:36 字数 375 浏览 10 评论 0原文

我有一些已解码的 json 对象,其中一个属性以“@”开头,我无法使用 php 访问该元素,因为它会引发错误。

                    [offers] => stdClass Object
                    (
                        [@attributes] => stdClass Object
                            (
                                [id] => levaka0B8a
                            )
                    )

我将如何访问属性?

I have some json object that I decoded, and one of the attributes starts with an "@" and I can't access the element with php because it throws an error.

                    [offers] => stdClass Object
                    (
                        [@attributes] => stdClass Object
                            (
                                [id] => levaka0B8a
                            )
                    )

How would I go about accessing attributes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

云柯 2024-10-18 14:52:36

您可以通过字符串访问它:

echo $obj->{'@attributes'}->id; // levaka0B8a

或变量:

$name = '@attributes';
echo $obj->$name->id;

有关如何定义和使用变量的更多信息,请参阅以下文档:

  • 变量基础知识 - 用于学习什么可以作为变量访问而无需使用字符串。
  • 变量变量 - 我们如何使用变量作为另一个变量的名称。这可能很危险,所以请小心行事

You can access it by a string:

echo $obj->{'@attributes'}->id; // levaka0B8a

Or a variable:

$name = '@attributes';
echo $obj->$name->id;

For more information on how variables are defined and used, see the following docs:

  • Variable Basics - Useful for learning what can be accessed as a variable without needing to use strings.
  • Variable Variables - How we used the variable to act as the name for another variable. This can be dangerous so tread carefully
2024-10-18 14:52:36

你可以这样做:

$object->{'@attributes'}

You could do this:

$object->{'@attributes'}
青瓷清茶倾城歌 2024-10-18 14:52:36

尝试使用,

$objSimpleXml->attributes()->id

示例代码参考

<?php
$string = <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
var_dump( $xml );
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?> 

Try to use,

$objSimpleXml->attributes()->id

Sample Code to Refer

<?php
$string = <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
var_dump( $xml );
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?> 
痞味浪人 2024-10-18 14:52:36

下面是 ircmaxwell 或 Richard Tuin 的直接访问,但是您可以使用第二个参数 true 解码 JSON,并插入接收数组,这可能更容易访问

direct access is below from ircmaxwell or Richard Tuin, however you can decode JSON with second param true and recive array insted what could be an easier to access

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文