Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate through DOM elements in PHP?

Tags:

dom

php

xml

I have an XML file loaded into a DOM document, I wish to iterate through all 'foo' tags, getting values from every tag below it. I know I can get values via

$element = $dom->getElementsByTagName('foo')->item(0); foreach($element->childNodes as $node){     $data[$node->nodeName] = $node->nodeValue; } 

However, what I'm trying to do, is from an XML like,

<stuff>   <foo>     <bar></bar>       <value/>     <pub></pub>   </foo>   <foo>     <bar></bar>     <pub></pub>   </foo>   <foo>     <bar></bar>     <pub></pub>   </foo>   </stuff> 

iterate over every foo tag, and get specific bar or pub, and get values from there. Now, how do I iterate over foo so that I can still access specific child nodes by name?

like image 704
Esa Avatar asked Oct 10 '08 15:10

Esa


1 Answers

Not tested, but what about:

$elements = $dom->getElementsByTagName('foo'); $data = array(); foreach($elements as $node){     foreach($node->childNodes as $child) {         $data[] = array($child->nodeName => $child->nodeValue);     } } 
like image 110
roryf Avatar answered Oct 02 '22 20:10

roryf