冠富商务通中文社区

 找回密码
 立即注册
查看: 6|回复: 0
打印 上一主题 下一主题
收起左侧

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

[复制链接]
跳转到指定楼层
楼主
发表于 2017-1-6 00:39:32 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
以下代码可以获取到指定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
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|关于我们|申请友链|Archiver|手机版|拘留所|冠富商务通

GMT+8, 2025-5-19 19:12 , Processed in 0.116007 second(s), 11 queries , Wincache On.

Powered by HCMS Version 2.0

© 2008-05-14 guanfu.net.cn

快速回复 返回顶部 返回列表