获取指定URL页面中的所有链接的PHP代码

以下代码可以获取到指定URL页面中的所有链接,即所有a标签的href属性:

// 获取链接的HTML代码
$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate('/html/body//a');

for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
echo $url.'<br />';
}

这段代码会获取到所有a标签的href属性,但是href属性值不一定是链接,我们可以在做个过滤,只保留http开头的链接地址:

// 获取链接的HTML代码
$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate('/html/body//a');

for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute('href');

// 保留以http开头的链接
if(substr($url, 0, 4) == 'http')
echo $url.'<br />';
}

原文地址:http://www.ludou.org/php-find-all-links-on-a-page.html

This entry was posted in Technology and tagged , , . Bookmark the permalink. 1,244 views

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>