PHP代码:获取指定URL页面中的所有链接
以下代码可以获取到指定URL页面中的所有链接,即所有a标签的href属性:
// 获取链接的HTML代码
1 $html = file_get_contents('http://www.example.com');
2
3 $dom = new DOMDocument();
4 @$dom->loadHTML($html);
5
6 $xpath = new DOMXPath($dom);
7 $hrefs = $xpath->evaluate('/html/body//a');
8
9 for ($i = 0; $i < $hrefs->length; $i++) {
10 $href = $hrefs->item($i);
12 $url = $href->getAttribute('href');
13 echo $url.'<br />';
14 }
PHP技术交流群 436753182
这段代码会获取到所有a标签的href属性,但是href属性值不一定是链接,我们可以在做个过滤,只保留http开头的链接地址:
// 获取链接的HTML代码
1 $html = file_get_contents('http://www.example.com');
2
3 $dom = new DOMDocument();
4 @$dom->loadHTML($html);
5
6 $xpath = new DOMXPath($dom);
7 $hrefs = $xpath->evaluate('/html/body//a');
8
9 for ($i = 0; $i < $hrefs->length; $i++) {
10 $href = $hrefs->item($i);
11 $url = $href->getAttribute('href');
12
13 // 保留以http开头的链接
14 if(substr($url, 0, 4) == 'http')
15 echo $url.'<br />';
16 }
PHP技术交流群 436753182