-1

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.

Miroslav
  • 546
  • 2
  • 9
  • 22
  • The manual has some nice [introductory examples](http://php.net/manual/en/simplexml.examples-basic.php), which include accessing basic attributes. – IMSoP Nov 01 '16 at 17:29

1 Answers1

7

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).

Dekel
  • 60,707
  • 10
  • 101
  • 129