![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements