Access an element's attributes with PHP's SimpleXML extension

Posted in PHP -

The PHP SimpleXML extension makes it easy to work with XML files by creating an object from the XML structure. To access an element's attributes, use the property() method for that element.

XML Example

The following examples use this as the XML string:

            <sometag myattribute="foo">first node</sometag>
            <sometag myattribute="bar">second node</sometag>

Get the "myattribute" attributes

First create the SimpleXML attribute. The above XML has already been loaded into a variable called $xml:

$xmlobj = new SimpleXMLElement($xml);

To access the value for the first <sometag> node from the first <item> do this:

echo $xmlobj->items->item[0]->sometag;

To access the "myattribute" attribute from the <sometag> node from the first <item> do this:

echo $xmlobj->items->item[0]->sometag->attributes()->myattribute;

To loop through all the <item> nodes and echo out the "myattribute" attribute and value for each of the <sometag> nodes do something along the lines of this:

foreach($xmlobj->items->item as $item) {
    echo "Attribute: " . $item->sometag->attributes()->myattribute . "\n
    echo "Value: " . $item->sometag . "\n\n";

This will output:

Attribute: foo
Value: first node

Attribute: bar
Value: second node

Related posts: