Miroslav Miroslav - 1 year ago 72
PHP Question

Get an attribute value using SimpleXML for PHP

I use SimpleXMLElement class for working with xml files in my project.

My question is: how to get an attribute value of some tag with some attribute? You may assume I know the name of the tag, the name of the attribute and it's location inside the xml file. For example, for such a string

<someTag cp="c2">
knowing values 'someTag' and 'cp' I want to obtain the string "c2".

Thanks is advance.

Answer Source

You can use the attributes() function on the node to get it's attributes:

$xml_str = '<xml>
        <someTag cp="c2">content</someTag>
$res = simplexml_load_string($xml_str);

$items = $res->xpath("//someTag");
var_dump((string) $items[0]->attributes()->cp);

The returned element is an SimpleXMLElement, so in order to use it I converted it to string (using the (string) cast).

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