This method uses the file_get_contents () function to capture all the content of the website, and then uses the regular expression to match the image in the content and download it. Save your own download. First, let's give an example. The code is as follows:
This method uses the file_get_contents () function to capture all the content of the website, and then uses the regular expression to match the image in the content and download it. Save your own download. First, let's give an example. The code is as follows:
$ Text = file_get_contents ("http://www.bao.fm ");
// Obtain all the img tags and store them to the two-dimensional array match
Preg_match_all ('/<[img | IMG]. *? Src = [\ '| \ "] (. *? (? : [\. Gif | \. jpg]) [\ '| \ "]. *? [\/]?> /', $ Text, $ match );
// Print the match
$ Houzhui = "./tp/". time (). rand (). ".". png;
$ Yuanname = getImage ($ match [1] [2], $ houzhui, tp );
// How to download images
Function getImage ($ url, $ filename = '', $ type = 0 ){
If ($ url = '') {return false ;}
If ($ filename = ''){
$ Ext = strrchr ($ url ,'.');
If ($ ext! Using '.gif '& $ ext! Else '.jpg ') {return false ;}
$ Filename = time (). $ ext;
}
// File storage path
If ($ type ){
$ Ch = curl_init ();
$ Timeout = 5;
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
$ Img = curl_exec ($ ch );
Curl_close ($ ch );
} Else {
Ob_start ();
Readfile ($ url );
$ Img = ob_get_contents ();
Ob_end_clean ();
}
$ Size = strlen ($ img );
// File size
$ Fp2 = @ fopen ($ filename, 'A ');
Fwrite ($ fp2, $ img );
Fclose ($ fp2 );
Return $ filename;
}
?>
This method has a drawback. for example, if a website has pagination, it cannot capture the content of the next page. you can also modify the code to see what the webpage link is like, then, the for loop file_get_contents () function puts the link into it.