beingalex
beingalex

Reputation: 2476

Iterate through elements with DOMDocument & DOMXPath

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.

Upvotes: 3

Views: 2199

Answers (1)

nickb
nickb

Reputation: 59699

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;
}

Upvotes: 6

Related Questions