简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM