John Cleary John Cleary - 1 year ago 98
PHP Question

Access @attributes data in SimpleXMLElement in PHP

Just wanted to start by saying I have read a LOT of the questions on this site about this exact problem, but I'm still struggling to apply it to my scenario. If someone could help me out, that'd be great! :)

I am trying to extract data from the following XML:

$myXML = '<?xml version="1.0" encoding="UTF-8"?>
<products><product uri="" id="1807" resource_type="current"><code>DEMO - MC700X/A</code><flags><inventoried>true</inventoried><editable_sell>false</editable_sell><master_model>false</master_model></flags><sell_price>0.00</sell_price><description>Apple MC700X/A Demo</description><inventory><available>7</available><reserved>0</reserved><coming_for_stock>2.0</coming_for_stock><coming_for_customer>0.0</coming_for_customer><warehouses>0</warehouses><total>7</total></inventory><product_photos/></product></products>';

I am using SimpleXML to put it into a PHP variable (object?) like this:

$xml = new SimpleXMLElement($myXML);

If I do a:

echo '<pre>';
echo '</pre>';

I get the following returned:

SimpleXMLElement Object
[product] => SimpleXMLElement Object
[@attributes] => Array
[uri] =>
[id] => 1807
[resource_type] => current

[code] => DEMO - MC700X/A
[flags] => SimpleXMLElement Object
[inventoried] => true
[editable_sell] => false
[master_model] => false

[sell_price] => 0.00
[description] => Apple MC700X/A Demo
[inventory] => SimpleXMLElement Object
[available] => 7
[reserved] => 0
[coming_for_stock] => 2.0
[coming_for_customer] => 0.0
[warehouses] => 0
[total] => 7

[product_photos] => SimpleXMLElement Object



Now, when I try to access that data programatically, the following works fine:

// This returns the value as expected
echo '<pre>';
echo '<br>';
echo '<br>';
echo '<br>';
echo '</pre>';

This returns:


But I need to be able to access the "id" tag in the base "product" element (i.e. the @attributes bit), but can't work it out. I've been reading a lot, and figured that I should be able to use the attributes() method, but I can't work it out exactly.

Trying this didn't work:

echo '<pre>';
echo '<br>';
echo '</pre>';

It just returns nothing. Can someone please help me? I want to be able to display the "id" tag.. i.e. what I would expect to be:

echo $xml['product']['@attributes']['id'];

obviously doesn't work either.


Answer Source

Did you try:

echo (string)$xml->product->attributes()->id;

That should give you access to the attributes.

If you have more than 1 product, it may be

echo (string)$xml->product[0]->attributes()->id;

You can also access the attributes using regular array notation such as:

$xml->product['id']; // instead of $xml->product->attributes()->id

See Example #5 from the SimpleXML Examples as well as the manual page on SimpleXMLElement::attributes() for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download