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

kyl*_*lex 2 php domdocument

可能重复:
用于获取A元素的href属性的正则表达式

这显示了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 />';
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*les 6

距离答案只有几英寸 - 你已经<a>在foreach循环中提取了标签.您正在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');
Run Code Online (Sandbox Code Playgroud)