I’m using SimpleXml in PHP and it works well for me.
Recently I had a problem when trying to grab a particular node (I hope that’s the right term).
Here’s a sample XML
<xml>
<attribute>
<item name="fun_level">
<value>Really Fun</value>
</item>
</attribute>
</xml>
So I’m using simplexml to get all the attributes, and run them through a loop, which all works fine. However, when I want to grab the “value” for an item with a particular name, I’m having trouble.
This works if I’m just trying to grab the value for the first item:
$value = (string)$attribute->item[0]->value;
Unfortunately I want to refer to a specific item, so I’m trying to do something like this, which isn’t working:
$value = (string)$attribute->item["@name='fun_level'"]->value;
I’m assuming I’m doing something wrong with my syntax where I refer to the name attribute of the item. Should I be using round brackets? braced? Do I need to do something different with the quotes?
Thanks for the help!
You need to use the
SimpleXMLElement::xpath()method.Also, see the manual page describing SimpleXML’s basic usage for more examples.