Consider the following PHP code
<?php
$html_data =
'<html><body>
<ol>
<li><strong>Question 1</strong> Answer1</li>
<li><strong>Question 2</strong> Answer2</li>
</ol></body></html>';
$doc = new DOMDocument();
$doc->loadHTML($html_data);
$xpath = new DOMXPath($doc);
$ols = $xpath->query('//ol');
$ol = $ols->item(0);
$lis = $ol->childNodes;
foreach ($lis as $li) {
echo $li->firstChild->nodeValue."<br />";
echo $li->lastChild->nodeValue."<br />";
//echo $li->childNodes->item(0)->nodeValue."<br />";
}
?>
If I remove the comment on the last line of this code and access the childNodes DOM Object Array, my foreach loop executes only once. However, if I access the same elements using firstChild and lastChild as shown above, I can successfully iterate over all the ‘li’ tags present.
I can’t make any sense of this at all. Is this a bug in PHP?
If you wouldn’t suprress your error reporting, you would have seen that you have a fatal error that breaks your script.
In order to work with the item method:
The only difference it was that the first script
Only throws Notice: Trying to get property of non-object, but the scripts continues.
As with method item() it throws a fatal error. (Fatal error: Call to a member function item() on a non-object). which kills your script.
For more details on how you should iterate on these nodesList (foreach vs. for) read the comments from these pages
And you especially have this issue because of the trailing space after the
<li>tags.It loops like this: first
<li>tag, then the space' ' DOMTextelement then the second<li>tag then the second' ' DOMTextelement.On the DOMText element it crashes. You could clear the spaces and it would work.