Nick Shears
Nick Shears

Reputation: 1133

How do I get certain details from a Simple XML Object?

I've retrieved data from an XML file like so

$response = simplexml_load_file($url);

print_r displays the following

SimpleXMLElement Object
(
[artist] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [type] => Group
                [id] => b9fb5447-7f95-4a6a-a157-afed2d7b9f4c
            )

        [name] => He Is Legend
        [sort-name] => He Is Legend
        [country] => US
        [area] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [id] => 489ce91b-6658-3307-9877-795b68554c98
                    )

                [name] => United States
                [sort-name] => United States
                [iso-3166-1-code-list] => SimpleXMLElement Object
                    (
                        [iso-3166-1-code] => US
                    )

            )

    )

)

So I can output fields like name and country by

echo $response->artist->name;
echo $response->artist->country;

However I'm stuck when it comes to being able to access data in the attribute arrays. How can I get the type of group from the first attributes array for example?

Edit

I'm also trying to return the details from a function like so

func getDetails($id) {

$response = simplexml_load_file('http://musicbrainz.org/ws/2/artist/'.$id);
$data = array();
$data['type'] = $response->artist->attributes()->type;
$data['country'] = $response->artist->country;

return $data;
}

print_r(getDetails());

Gives me

MusicBrainz Object
(
)

Upvotes: 0

Views: 121

Answers (1)

Amal Murali
Amal Murali

Reputation: 76656

You can access them using the attributes() method:

echo $response->artist->attributes()->type;

The example #5 in the SimpleXML documentation shows another example.

Upvotes: 1

Related Questions