Search code examples
phpstdclass

How extract @attributes from stdClass Object?


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.


Solution

  • 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'];