
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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.
- Related Articles
- Iterate through elements of HashSet in Java
- Iterate through elements of TreeSet in Java
- Iterate through elements of Java LinkedHashSet
- How can I iterate through two lists in parallel in Python?
- Java Program to Iterate through Elements of HashMap
- Golang Program to Iterate through Elements of Dictionary
- Iterate through elements of a LinkedList using a ListIterator in Java
- How to iterate through and access the JSON array elements using Rest Assured?
- How to iterate through Java List?
- How do I chain methods in PHP?
- How do I iterate over a sequence in reverse order in Python?
- Iterate through ArrayList in Java
- How to correctly iterate through getElementsByClassName() in JavaScript?
- How to iterate through a dictionary in Python?
- How to iterate through a list in Python?

Advertisements