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 use it directly The simplest code implementation:
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 You can call the code like this to download pictures:
$spider = new Spider(); foreach ( $images as $url ) { $spider->downloadImage($url); }
The above is the detailed content of Detailed explanation of method examples for downloading remote images and saving them locally in PHP. For more information, please follow other related articles on the PHP Chinese website!