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. '
';
- }
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. '
';
- }
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/";//URL address to collect 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 the URL address page
- while (!feof ($FP)) $contents. =fread ($fp, 1024x768);
- $pattern = "|href=[' \"]? ([^ '\"]+) ['\" ]| U ";
- Preg_match_all ($pattern, $contents, $REGARR, preg_set_order);//use regular matches for all href=
- for ($i =0; $i
- if (!eregi ("://", $REGARR [$ I][1])//Determines 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]. "
";//root directory
- Else
- echo "link". ($i + 1). ":" $base. $REGARR [$i][1]. "
";//Current directory
- Else
- echo "link". ($i + 1). ":" $regArr [$i][1]. "
";//relative path
- }
- fclose ($fp);
- ?
Form:http://www.uphtm.com/php/253.html
The above describes the PHP get all the links in the specified URL page, including the contents of the content, I hope the PHP tutorial interested in a friend helpful.