This article mainly introduces the PHP implementation of remote image download method, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.
When using PHP as a simple crawler, we often encounter the need to download remote images, so the following is a simple implementation of the requirements.
1. Using Curl
For example, we have the following two pictures:
$images = [ ' https://dn-laravist.qbox.me/2015-09-22_00-17-06j.png ', ' https://dn-laravist.qbox.me/ 2015-09-23_00-58-03j.png '];
In the first step, we can directly use the simplest code implementations:
function Download ($url, $path = ' images/') { $ch = Curl_init (); curl_setopt ($ch, Curlopt_url, $url); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_connecttimeout,); $file = curl_exec ($ch); Curl_close ($ch); $filename = PathInfo ($url, pathinfo_basename); $resource = fopen ($path. $filename, ' a '); Fwrite ($resource, $file); Fclose ($resource);}
That's what you can do when you download a remote image:
foreach ($images as $url) { download ($url);}
2. Encapsulation of a class
After the idea is clear, we can encapsulate this basic function in a class:
Class Spider {public function downloadimage ($url, $path = ' images/') { $ch = Curl_init (); curl_setopt ($ch, Curlopt_url, $url); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_connecttimeout,); $file = curl_exec ($ch); Curl_close ($ch); $filename = PathInfo ($url, pathinfo_basename); $resource = fopen ($path. $filename, ' a '); Fwrite ($resource, $file); Fclose ($resource); }}
We can also optimize this a little bit:
Public Function Downloadimage ($url, $path = ' images/') { $ch = Curl_init (); curl_setopt ($ch, Curlopt_url, $url); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, Curlopt_connecttimeout,); $file = curl_exec ($ch); Curl_close ($ch); $this->saveasimage ($url, $file, $path); } Private Function Saveasimage ($url, $file, $path) { $filename = PathInfo ($url, pathinfo_basename); $resource = fopen ($path. $filename, ' a '); Fwrite ($resource, $file); Fclose ($resource); }
After encapsulation into a class, we can call the code to download the image:
$spider = new Spider (), foreach ($images as $url) { $spider->downloadimage ($url);}
This way, the basic remote image download is OK.