Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through elements with DOMDocument & DOMXPath

Tags:

dom

php

xpath

I am trying to iterate through every child element of the containing div:

$html = '    <div id="roothtml">
<h1>
Introduction</h1>
<p>text</p>
<h2>
text</h2>
<p>
test</p>
</div>';

And I have this PHP:

$dom = new DOMDocument();
$dom->loadHTML($html);

$dom->preserveWhitespace = false;

$xpath = new DOMXPath($dom);
$els = $xpath->query("/div");
print_r($els);   

All I get though is DOMNodeList Object ( )

Having looked at the IBM tutorial I should be getting an array. What is it I am doing wrong?

Any help is appreciated.

like image 919
beingalex Avatar asked Jul 16 '26 06:07

beingalex


1 Answers

You're using the wrong query string, you should be using //div.

Iterate over the list like this:

$els = $xpath->query("//div");
foreach( $els as $el) {
    echo $el->textContent;
}
like image 106
nickb Avatar answered Jul 17 '26 19:07

nickb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!