How do I iterate through DOM elements in PHP?

Following is the XML data (input) −

<other data>
   <foo> <bar></bar>
   <pub></pub> </foo>
   <bar></bar> <pub></pub>
   <bar></bar> <pub></pub>
</other data>

Iterating through the elements in the DOM object.


$elements = $dom->getElementsByTagName('foo');
$data = array();
foreach($elements as $node){
   foreach($node->childNodes as $child) {
      $data[] = array($child->nodeName => $child->nodeValue);


This will produce the following output −

Every ‘foo’ tag will be iterated over and specific ‘bar’ and ‘pub’ value will be obtained, 
i.e specific child nodes can be accessed by their names itself.

The elements in the XML file are obtained by running a foreach loop over all the nodes in the XML file. Inside the foreach loop, the child node of the main node is referenced, and the child node’s child value can be accessed.

Updated on: 09-Apr-2020


Kickstart Your Career

Get certified by completing the course

Get Started