以下代码可以获取到指定 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 />';
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)