php获取页面所有链接

以下两种方式都会获取a标签的href属性,但是href里面内容不一定是链接,所以还要做后续处理。

方式1

dom对象方式

$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 />';
}

方式2

正则表达式匹配

$html = file_get_contents('http://www.example.com');

$link_pattern = "/<a.*?href=['"](.*?)['"].*?<\/a>/i";
preg_match_all($link_pattern, $content, $matches);

for ($i = 0; $i < count($matches[1]); $i++) {
    echo $matches[1][$i] . "<br />";
}
如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注