How to parse value `@attribute` from a SimpleXMLObject in PHP

240 views Asked by At

I am trying to parse the starkoverflow.com/feeds/tag/{$tagName}. This is my code:

<?php
    $xml = file_get_contents("http://stackoverflow.com/feeds/tag/php");
    $simpleXml = simplexml_load_string($xml);
    $attr = $simpleXml->entry->category->@attributes;

?>

When I execute the above code it gives me a error, Parse error: syntax error, unexpected '@', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in D:\wamp\www\success\protoT.php on line 4

So, My question is how to get the array of the @attributes?

Scrrenshot

2

There are 2 answers

3
Mark Baker On BEST ANSWER

You use the appropriately documented method: attributes()

$attr = $simpleXml->entry->category->attributes();

Except that $simpleXml->entry->category is an array, so you need to specify which entry in the array you want to access:

$attr = $simpleXml->entry->category[0]->attributes();

EDIT

Unless, as I have just learned, you only need to reference the first element

0
IMSoP On

The key is, to realise there is no spoon array.

To get all the attributes as an array, you can use the attributes() method:

$all_attributes = $simpleXml->entry->category->attributes();

However, most of the time, what you really want is a particular attribute, in which case you just use array key notation:

$id_attribute = $simpleXml->entry->category['id'];

Note that this returns an object; when passing it around, you generally want to have just the string representing its value:

$id_value = (string)$simpleXml->entry->category['id'];

The above will assume you always want the first <category> element in the first <entry>, even if there are multiple. It is actually short-hand for specifying the 0th item (which works even if there is only one of each element):

$id_value = (string)$simpleXml->entry[0]->category[0]['id'];

Or, of course, looping over each set (again, it doesn't matter if there are one or multiple, the foreach will still work):

foreach ( $simpleXml->entry as $entry ) {
    foreach ( $entry->category as $category ) {
        $id_value_for_this_category = (string)$category['id'];
    }
}