使用domDocument和解析信息,我想获得'a'标签的'href'内容

时间:2011-03-11 21:11:33

标签: php domdocument

  

可能重复:
  Regular expression for grabbing the href attribute of an A element

这会显示a标记之间的内容,但我想要一种方法来获取href内容。

有没有办法使用domDocument做到这一点?

$html = file_get_contents($uri);
$html = utf8_decode($html);

/*** a new dom object ***/
$dom = new domDocument;

/*** load the html into the object ***/
@$dom->loadHTML($html);

/*** discard white space ***/
$dom->preserveWhiteSpace = false;

/*** the table by its tag name ***/
$tables = $dom->getElementsByTagName('table');

/*** get all rows from the table ***/
$rows = $tables->item(0)->getElementsByTagName('tr');

/*** loop over the table rows ***/
foreach ($rows as $row)
{
    $a = $row->getElementsByTagName('a');
    /*** echo the values ***/
    echo $a->item(0)->nodeValue.'<br />';
    echo '<hr />';
}

2 个答案:

答案 0 :(得分:6)

距离答案只有几英寸 - 您已经提取了foreach循环中的<a>标签。您正在DOMNodeList中抓取所有这些内容,因此该列表中的每个项目都是DOMElement的实例,其中有一个名为getAttribute的方法。

$a->item(0)->getAttribute('href')将包含href属性的字符串值。多田!


您可能会获得一个空节点列表。您可以通过检查列表中的第一项是否为元素来解决此问题。

$href = null;
$first_anchor_tag = $a->item(0);
if($first_anchor_tag instanceof DOMElement)
    $href = $first_anchor_tag->getAttribute('href');

答案 1 :(得分:0)

echo $a->getAttributeNode('href')->nodeValue."<br />";
相关问题