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

992

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!

102

Answer

Solution:

You can do it usingchildren() 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

People are also looking for solutions to the problem: php - Feedback Form jQuery returns no data

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.