PHP DOM 获取 TABLE 之间的 HREF 属性

PHP DOM GET HREF ATTRIBUTE BETWEEN TABLE

我正在尝试从 table 中获取多个 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 />';
   } 
?>

我收到这个错误

Fatal error: Uncaught Error: Call to a member function getElementsByTagName() on null

getAttribute 导致错误

有人可以帮我解决吗谢谢

由于之前访问$cols数组都有@抑制错误,所以这是第一个报错

如果没有找到 <td> 元素(例如 header 行),一个简单的解决方法是跳过其余代码...

foreach ($rows as $row)
{
    $cols = $row->getElementsByTagName('td');
    if ( count($cols) == 0 )    {
        continue;
    }

您也可以使用 XPath,并且只使用包含 <td> 个标签的 select <tr> 个标签。

您的 $rows 是“<table> 内的所有 <tr>”的结果。它不仅捕获了 table body 中的 <tr>,它还捕获了你的 table 头中的那个,它里面没有 <td>。因此,当阅读该行时,$cols->item(0)$cols->item(1) 都得到了 NULL.

当您的代码未在项目中找到 ->nodeValue 属性时,您应该接受提示(因此您添加了 @ 符号以抑制警告)。

尝试改变这个:

$rows = $tables->item(0)->getElementsByTagName('tr'); 

进入这个:

$rows = $tables
        ->item(0)->getElementsByTagName('tbody')
        ->item(0)->getElementsByTagName('tr');

现在它正在搜索您的 <tbody> 中的 <tr> 并且应该可以解决您与此特定 HTML.

的问题

要获得更健壮的代码,您应该在对变量执行操作之前检查变量。类型检查或计数检查会很好。