How to access a member of an stdClass in PHP that starts with an @
Asked Answered
G

4

13

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?

Gervais answered 11/1, 2011 at 17:2 Comment(2)
This rather looks like it was some weird conversion from a SimpleXmlElement to a StdClass. Can you please clarify how you got the dump?Altissimo
this is conversion from JSON not XML :)Stickleback
A
31

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
Airhead answered 11/1, 2011 at 17:5 Comment(0)
M
9

You could do this:

$object->{'@attributes'}
Microcline answered 11/1, 2011 at 17:4 Comment(0)
C
3

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";
}
?> 
Cassondra answered 16/2, 2011 at 10:31 Comment(0)
S
2

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

Stickleback answered 11/1, 2011 at 17:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.