Reputation: 221
I have an isolated problem with DOMDocument Where the following message appears in the log file:
PHP Fatal error: Call to a member function getElementsByTagName() on a non-object
The isolated problem code looks like this:
$data = "<html><head><title></title></head><body><table id=\"rang-table\"><thead> <tr> <th data-priority=\"2\">Rang</th> <th data-priority=\"1\">Name</th> <th data-priority=\"3\">Punkte</th> </tr> </thead> <tbody> <tr><td>1</td><td>Nadja F.</td><td align=\"right\">-9.44</td></tr><tr><td>2</td><td>Karsten G.</td><td align=\"right\">-2.71</td></tr><tr><td>3</td><td>Bjoern K.</td><td align=\"right\">-1.97</td></tr><tr><td>4</td><td>Stefanie A.</td><td align=\"right\">-0.74</td></tr><tr><td>5</td><td>Christian S.</td><td align=\"right\">1.94</td></tr><tr><td>6</td><td>Rene H.</td><td align=\"right\">2.68</td></tr><tr><td>7</td><td>Boris H.</td><td align=\"right\">10.24</td></tr> </tbody> </table></body></html>";
$dom = new domDocument;
@$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(1)->getElementsByTagName('tr');
$betreffzeile = "";
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
$betreffzeile.=$cols[2];
}
echo $betreffzeile;
Upvotes: 1
Views: 942
Reputation: 41885
Just to point out the obvious, the indices starts at zero, right now you only have that single table which means it'll fall under 0
:
$tables = $dom->getElementsByTagName('table'); // returns DOMNodeList
$rows = $tables->item(0)->getElementsByTagName('tr'); // point to first element index 0
It seems you're trying to get the third <td>
values inside the <tbody>
why not point to it directly:
$tbody = $dom->getElementsByTagName('tbody');
$rows = $tbody->item(0)->getElementsByTagName('tr');
$betreffzeile = "";
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
$betreffzeile .= $cols->item(2)->nodeValue . '<br/>';
}
echo $betreffzeile;
Upvotes: 1
Reputation: 700
The array returned by getElementsByTagName
is zero-indexed, meaning that in this case, $tables[1]
does not exist (you only have one table in the HTML, and that table is referred to as $tables[0]
) so you need to change the definition of $rows
to this:
$rows = $tables->item(0)->getElementsByTagName('tr');
You also have an error in the loop; you can't refer to a DOMNodelist with an index like you are. You'd need to change the assignment of $betreffzeile
to this: $betreffzeile.=$cols->item(2)->nodeValue;
Hope this helps.
Upvotes: 2