php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #64104 Accessing childNodes of DOM element fails
Submitted: 2013-01-30 10:15 UTC Modified: 2013-01-30 10:38 UTC
From: me at gowthams dot in Assigned:
Status: Not a bug Package: DOM XML related
PHP Version: 5.4.11 OS: All
Private report: No CVE-ID: None
 [2013-01-30 10:15 UTC] me at gowthams dot in
Description:
------------
I found this error while trying to parse an ordered list. When I access the firstChild or the lastChild of a DOM object that is in turn derived from another DOM object , the value is printed perfectly. 

However, when I try to access childDomObject->childNodes->item(0), the code fails.

Test script:
---------------
<?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 />";
}

Expected result:
----------------
Question 1 Answer1<br />
Question 2 Answer2<br />

Actual result:
--------------
Question 1<br />


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-01-30 10:38 UTC] johannes@php.net
-Status: Open +Status: Not a bug
 [2013-01-30 10:38 UTC] johannes@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

When enabling error reporting your script prints

Question 1<br />
Fatal error: Call to a member function item() on a non-object in - on line 22


When looking a bit close, i.e. doing

foreach ($lis as $li) {
  var_dump($li->nodeName);
}

You get output like

string(2) "li"
string(5) "#text"
string(2) "li"
string(5) "#text"

which shows you there are text nodes after the <li> tags,
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Fri Dec 04 02:01:23 2020 UTC