使用domDocument并解析信息,我想获取'a'标签的'href'内容 [英] Using domDocument, and parsing info, I would like to get the 'href' contents of an 'a' tag

查看:182
本文介绍了使用domDocument并解析信息,我想获取'a'标签的'href'内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Possible Duplicate:
Regular expression for grabbing the href attribute of an A element

这显示了a标记之间的内容,但是我也想获得一种href内容的方式.

This displays the what is between the a tag, but I would like a way to get the href contents as well.

是否可以使用domDocument做到这一点?

Is there a way to do that using the 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 />';
}

推荐答案

您距离答案只有几英寸之遥-您已经在foreach循环中提取了<a>标记.您正在 DOMNodeList 中捕获所有这些元素,因此该列表将是 DOMElement 的实例,该实例具有称为 getAttribute .

You're mere inches away from the answer -- you've already extracted the <a> tags inside your foreach loop. You're grabbing all of them in a DOMNodeList, so each item in that list will be an instance of DOMElement, which has a method called getAttribute.

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

$a->item(0)->getAttribute('href') will contain the string value of the href attribute. Tada!

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

It's possible that you might get an empty node list. You can work around this by checking that the first item in the list is an element.

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

这篇关于使用domDocument并解析信息,我想获取'a'标签的'href'内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆