Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over DOMDocument

Tags:

I am following the suggestion from this question Robust, Mature HTML Parser for PHP, about parsing html that may be malformed with DOMDocument.

Is there any easy way to loop over the parsed document? So I would like to loop over html like this.

$html='<ul>          <li>value1</li>          <li>value1</li>          <li>value3             <p>subvalue</p>          </li>         </ul>         <p>hello world</p>';  $doc = new DOMDocument(); $doc->loadHTML($html); ??? foreach (??? as $node) {   print $node->nodeName.':'.$node->nodeValue; } 

And get results somewhat like this.

 ul:  li:value1  li:value2  li:value3  p:subvalue  p:hello world 

Using $doc->childNodes by itself doesn't really do what I want. Since it doesn't seem to go down to lower branches in the tree. I used the code suggested by halfdan and I get results like this.

html: html:value1          value1          value3             subvalue          hello world 
like image 782
Zoredache Avatar asked May 26 '10 02:05

Zoredache


People also ask

How do I iterate over a DOM element?

To loop through all DOM elements: Use the getElementsByTagName() method to get an HTMLCollection containing all DOM elements. Use a for...of loop to iterate over the collection.

How do you iterate over elements in HTML?

After selecting elements using the querySelectorAll() or getElementsByTagName() , you will get a collection of elements as a NodeList . To iterate over the selected elements, you can use forEach() method (supported by most modern web browsers, not IE) or just use the plain old for-loop.

How do you get an array of all the DOM elements with a certain selector?

To get all DOM elements by an attribute, use the querySelectorAll method, e.g. document. querySelectorAll('[class="box"]') . The querySelectorAll method returns a NodeList containing the elements that match the specified selector.


1 Answers

Try this:

$doc = new DOMDocument(); $doc->loadHTML($html); showDOMNode($doc);  function showDOMNode(DOMNode $domNode) {     foreach ($domNode->childNodes as $node)     {         print $node->nodeName.':'.$node->nodeValue;         if($node->hasChildNodes()) {             showDOMNode($node);         }     }     } 
like image 76
halfdan Avatar answered Sep 30 '22 12:09

halfdan