This article mainly introduces the method of downloading remote images in PHP. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
When using PHP to make a simple crawler, we often encounter the need to download remote images, so let’s simply implement this need.
1. Use 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 to implement:
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, 30); $file = curl_exec($ch); curl_close($ch); $filename = pathinfo($url, PATHINFO_BASENAME); $resource = fopen($path . $filename, 'a'); fwrite($resource, $file); fclose($resource); }
Then when downloading remote images, you can do this:
foreach ( $images as $url ) { download($url); }
2. Encapsulate a class
After clarifying the idea, we can encapsulate this basic function Into 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, 30); $file = curl_exec($ch); curl_close($ch); $filename = pathinfo($url, PATHINFO_BASENAME); $resource = fopen($path . $filename, 'a'); fwrite($resource, $file); fclose($resource); } }
Now, we can also optimize it a little like this:
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, 30); $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 encapsulating it into a class, we can call the code to download the image like this:
$spider = new Spider(); foreach ( $images as $url ) { $spider->downloadImage($url); }
In this way, basic remote image downloading is OK.
Related recommendations:
PHPDownload remoteDetailed explanation of the definition and usage of file classes
##PHP Download remotePictures and save them to local code
PHP implementationDownload remoteFile related code
The above is the detailed content of Detailed explanation of how to download remote images and save them locally using PHP. For more information, please follow other related articles on the PHP Chinese website!