Form:http://www.uphtm.com/php/253.html
This thing in fact, we are commonly used by developers, used to do a crawl other website friendship connection used, and today saw a friend organized a PHP get the specified URL page of all the link functions, organize us to see it together.
The following code can get all the links in the specified URL page, which is the href attribute of all the A tags:
- Get the HTML code for the link
- $html = file_get_contents (' http://www.111cn.net ');
- $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/> ';
- }
This code gets all the href attributes of the a tag, but the href attribute value is not necessarily a link, we can do a filter and keep only the link address at the beginning of the http:
- Get the HTML code for the link
- $html = file_get_contents (' http://www.111cn.net ');
- $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 ');
- Keep links that start with HTTP
- if (substr ($url, 0, 4) = = = ' http ')
- echo $url. ' <br/> ';
- }
The fopen () function reads all the links in the specified Web page and counts the number of pages, where it is appropriate to use this code, this example to read Baidu home page for example, to find out all the links in the homepage of Baidu, the code has been tested, fully available:
- <?
- if (empty ($url)) $url = "http://www.baidu.com/";//need to collect the URL address of the link
- $site =substr ($url, 0,strpos ($url, "/", 8));
- $base =substr ($url, 0,strrpos ($url, "/") +1);//directory where the file is located
- $fp = fopen ($url, "R");//Open URL Address page
- while (!feof ($FP)) $contents. =fread ($FP, 1024);
- $pattern = "|href=["]? ([^ ' \ "]+) [' \ ']| U ";
- Preg_match_all ($pattern, $contents, $REGARR, preg_set_order);//use regular match all href=
- for ($i =0; $i <count ($REGARR); $i + +) {//Find out all matching links
- if (!eregi ("://", $REGARR [$i][1])//Determine whether it is a relative path, that is, whether there is://
- if (substr ($regArr [$i][1],0,1) = = "/")//is the root directory of the site
- echo "link". ($i + 1). ":" $site. $REGARR [$i][1]. " <br/> ";//root directory
- Else
- echo "link". ($i + 1). ":" $base. $REGARR [$i][1]. " <br/> ";//Current directory
- Else
- echo "link". ($i + 1). ":" $regArr [$i][1]. " <br/> ";//relative path
- }
- Fclose ($FP);
- ?>
Form:http://www.uphtm.com/php/253.html
PHP gets all the links in the specified URL page