获取 HTML 表格单元格中 <a> 标签的 href 属性

问题描述 投票:0回答:1

我正在尝试使用 php 的 domDocument 从某些数据的 url 中提取 href。

以下为网址拉锚,但我想要网址

$events[$i]['race_1'] = trim($cols->item(1)->nodeValue); 

如果有帮助的话,这里有更多代码。

   // initialize loop
   $i = 0;
   // new dom object  
   $dom = new DOMDocument();  
   
   //load the html  
   $html = @$dom->loadHTMLFile($url);  
   //discard white space   
   $dom->preserveWhiteSpace = true;   
   
   //the table by its tag name  
   $information = $dom->getElementsByTagName('table'); 
   $rows = $information->item(4)->getElementsByTagName('tr');  

   foreach ($rows as $row)   
   { 
    $cols = $row->getElementsByTagName('td');   
    $events[$i]['title'] = trim($cols->item(0)->nodeValue); 
    $events[$i]['race_1'] = trim($cols->item(1)->nodeValue);   
$events[$i]['race_2'] = trim($cols->item(2)->nodeValue);  
$events[$i]['race_3'] = trim($cols->item(3)->nodeValue);
$date = explode('/', trim($cols->item(4)->nodeValue));
$events[$i]['month'] = $date['0'];
$events[$i]['day'] = $date['1'];
$citystate = explode(',', trim($cols->item(5)->nodeValue));   
$events[$i]['city'] = $citystate['0'];
$events[$i]['state'] = $citystate['1'];
$i++;
   }
   print_r($events);

这是TD标签的内容

<td width="12%" align="center" height="13"><!--mstheme--><font face="Arial"><span lang="en-us"><b>
          <font style="font-size: 9pt;" face="Verdana">
          <a linkindex="18" target="_blank" href="results2010/brmc5k10.htm">Overall</a>    

php dom html-parsing domdocument text-extraction
1个回答
11
投票

更新,我看到问题了。您需要从

a
中获取
td
元素的列表。

$cols = $row->getElementsByTagName('td');
// $cols->item(1) is a td DOMElement, so have to find anchors in the td element
// then get the first (only) ancher's href attribute
// (chaining looks long, might want to refactor/check for nulls)
$events[$i]['race_1'] = trim($cols->item(1)->getElementsByTagName('a')->item(0)->getAttribute('href');

非常确定您应该能够就该项目致电

getAttribute()
。您可以验证该项目是否为nodeType
XML_ELEMENT_NODE
;如果该项目不是 DOMElement,它将返回一个空字符串。

<?php
// ...
$events[$i]['race_1'] = trim($cols->item(1)->getAttribute('href'));
// ...   
?>

参见相关:php中的DOMNode到DOMElement

© www.soinside.com 2019 - 2024. All rights reserved.