Php captures website images and saves them locally

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.