Search code examples
phpxmlsimplexml

Accessing nth element of XML with different node names in PHP with SimpleXml


When all the children of an XML node have the same name, using SimpleXml in PHP you can access the nth element easily with $xml->foo[$nth]. ( Accessing nth element of XML in PHP with SimpleXml ) How can I get the nth element if children have different names?

For example in an xml like this:

<?xml version="1.0"?>
<root>
  <foo id="11" />
  <foo id="2" />
  <bar id="10" />
  <foo id="8" />
</root>

I'd like to know if the third element is a 'foo' or a 'bar' without iterating all the nodes.

Thanks in advance!


Solution

  • You can do it using children() method:

    $xml = simplexml_load_file('file.xml');
    $childrens = $xml->children();
    var_dump($childrens[1]); // <foo id="2" />
    var_dump($childrens[2]); // <bar id="10" />
    

    Link: http://php.net/manual/en/simplexmlelement.children.php