【发布时间】:2020-11-03 11:16:19
【问题描述】:
我正在尝试从这样的表中获取多个 href
<table class="table table-bordered table-hover">
<thead>
<tr>
<th class="text-center">No</th>
<th>TITLE</th>
<th>DESCRIPTION</th>
<th class="text-center"><span class="glyphicon glyphicon-download-alt"></span></th>
</tr>
</thead>
<tbody>
<tr data-key="11e44c4ebff985d08ca5313231363233">
<td class="text-center" style="width: 50px;">181</td>
<td style="width:auto; white-space: normal;"><a href="link-1.html">Link 1</a></td>
<td style="width:auto; white-space: normal;">Lorem ipsum dolor 1</td>
<td class="text-center" style="width: 50px;"><a href="link-1.pdf" title="Download" target="_blank"><img src="https://example.com/img/pdf.png" width="15" height="20" alt="myImage"></a></td>
</tr>
<tr data-key="11e44c4e4222d630bdd2313231323532">
<td class="text-center" style="width: 50px;">180</td>
<td style="width:auto; white-space: normal;"><a href="link-2.html">Link 2</a></td>
<td style="width:auto; white-space: normal;">Lorem ipsum dolor 2</td>
<td class="text-center" style="width: 50px;"><a href="link-2.pdf" title="Download" target="_blank"><img src="https://example.com/img/pdf.png" width="15" height="20" alt="myImage"></a></td>
</tr>
</tbody>
</table>
我尝试这样的 PHP DOM
<?php
$html = file_get_contents('data2.html');
$htmlDom = new DOMDocument;
$htmlDom->preserveWhiteSpace = false;
$htmlDom->loadHTML($html);
$tables = $htmlDom->getElementsByTagName('table');
$rows = $tables->item(0)->getElementsByTagName('tr');
foreach ($rows as $row)
{
$cols = $row->getElementsByTagName('td');
echo @$cols->item(0)->nodeValue.'<br />';
echo @$cols->item(1)->nodeValue.'<br />';
echo trim($cols->item(1)->getElementsByTagName('a')->item(0)->getAttribute('href')).'<br />';
echo @$cols->item(2)->nodeValue.'<br />';
echo trim($cols->item(3)->getElementsByTagName('a')->item(0)->getAttribute('href')).'<br />';
}
?>
我收到此错误
致命错误:未捕获的错误:在 null 上调用成员函数 getElementsByTagName()
getAttribute 导致错误
谁能帮帮我,谢谢
【问题讨论】:
-
很明显,某些东西(
$tables->item(0)或$cols->item(1)或$cols->item(3))是 null。var_dump并检查。 -
因为第一个
tr不包含任何td标记(在thead中)。 -
nodeValue 没问题,但无法获取 href 的属性
-
会有所帮助,如果你能说,哪个 getElementsByTagName 导致错误
标签: php dom html-table attributes getelementsbytagname