How do I iterate through DOM elements in PHP?


Following is the XML data (input) −

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

Iterating through the elements in the DOM object.

Example

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

Output

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

938 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements