Miroslav Miroslav - 1 month ago 5
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

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

$xml_str = '<xml>
    <node>
        <someTag cp="c2">content</someTag>
    </node>
</xml>';
$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).