Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing @attribute from php object

Tags:

php

I'm trying to access values from a PHP object returned from an API. I am trying to get the 'total' atribute.

stdClass Object
(
    [@attributes] => stdClass Object
        (
            [status] => ok
        )

    [invoices] => stdClass Object
        (
            [@attributes] => stdClass Object
                (
                    [page] => 1
                    [per_page] => 25
                    [pages] => 1
                    [total] => 5
                )

My returned object is stored in a variable called $list.

$list->invoices->attributes->total

I'm trying to echo / print_r that, but getting nothing?

Any help is appreciated!

like image 724
Alpinestar22 Avatar asked May 18 '13 23:05

Alpinestar22


3 Answers

The @ is a part of the property name, you can't just ignore it.

echo $list->invoices->{'@attributes'}->total;
like image 89
Niet the Dark Absol Avatar answered Oct 13 '22 00:10

Niet the Dark Absol


$total = $list->invoices->attributes()->total;
like image 37
Steven Teo Avatar answered Oct 13 '22 01:10

Steven Teo


As it turns out, you don't need to even specify @attributes to read this data. The key trick to get to it is to cast the result as a string.

So, I know it seems strange, but this will work in this case:

 echo (string)$list->invoices['total'];
like image 30
Darrell Duane Avatar answered Oct 13 '22 00:10

Darrell Duane