-3

How i can extract the attributes from a stdClass Object? I have the variable $data. Doing a print_r to it i get:

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

    [text] => text
)

No problem when i try to read text. But when i try to read id and title with $data["id"] and $data["title"] get error:

Fatal error: Uncaught Error: Cannot use object of type stdClass as array in...

How i can solve it? The unique chance is convert in array using json_encode/json_decode? Not there is a solution more object oriented?

Thanks.

Marcello Impastato
  • 2,263
  • 5
  • 30
  • 52
  • Does this answer your question? [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – El_Vanja Apr 08 '21 at 14:28
  • 1
    Searching for that error would have revealed that you're not dealing with an array. How to get an array instead of an object is explained in the link above. – El_Vanja Apr 08 '21 at 14:29
  • 1
    Are you reading XML? If so, then look into SimpleXML to help. – Nigel Ren Apr 08 '21 at 14:30
  • 3
    This looks suspiciously like you've converted XML to a SimpleXML object, then converted it to JSON, and converted it back to a much less useful object. If so, don't. Read [the usage examples for SimpleXML in the manual](https://www.php.net/manual/en/simplexml.examples.php) instead. – IMSoP Apr 08 '21 at 14:36

1 Answers1

4

Normally, you'd just use the name of the attribute like this:

$data->foo

However, since your attribute name @attributes contains a special character, you have to use this extended syntax:

$data->{'@attributes'}

Then, you can further reference its subkeys:

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

Alternatively, you could pass a truthy value as the second argument of json_decode() and then you'll get an array instead of an object:

$data = json_decode($raw, true);
$id = $data['@attributes']['id'];
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98