php - PHP DOM 获取表之间的 HREF 属性
问题描述
我正在尝试从这样的表中获取多个 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 导致错误
有人可以在这里帮我吗谢谢
解决方案
由于之前对$cols
数组的访问都必须@
抑制错误,这是第一个抱怨的。
<td>
如果没有找到任何元素(例如标题行),一个简单的解决方法是跳过其余代码......
foreach ($rows as $row)
{
$cols = $row->getElementsByTagName('td');
if ( count($cols) == 0 ) {
continue;
}
您也可以使用 XPath 并仅选择<tr>
包含标签的<td>
标签。
推荐阅读
- react-native - 反应导航使用 redux 使用自定义组件定义抽屉导航
- flutter - 通过单击按钮在 Flutter 中停止 while 循环
- python - Python 方法(在哪里可以找到其他资源)
- html - 在父div中水平居中div?
- python-3.x - 如何使用 matplotlib 和 gridspec 将 pickle 文件中的轴添加到现有图形?
- python - 运行代码时出现UnboundLocalError,这根本没有意义
- angular - 出现错误 RangeError:尝试导入共享模块 IONIC 时超出了最大调用堆栈大小
- python-3.x - 为什么索引如此有效?
- javascript - 如何分发带有子模块的 es6 包
- css - 有没有办法减小 Divi style.css 和 style.dev.css 的大小?