Blogger Information
Blog 33
fans 0
comment 0
visits 25880
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php如何下载远程图片呢??
非常缪
Original
649 people have browsed it

php远程下载图片经常用到,如何实现呢??

原理:通过curl请求url,将请求返回的文件流  写入到指定的路径中

<?php
* 在使用 PHP 做简单的爬虫的时候,我们经常会遇到需要下载远程图片的需求,所以下面来简单实现这个需求。
*/

//比如我们有下面这两张图片:
$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'
];

class Spider
{

   //定义下载图片  用于发送url
   public function downloadImage($url, $path = 'images/')
   {
       $ch = curl_init();
       //以url的形式 进行请求
       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);
   }
}

//封装成类之后,我们可以这样调用代码来下载图片:这样,对付基本的远程图片下载就OK了。
$spider = new Spider();
foreach ($images as $url) {
   $spider->downloadImage($url);
}

                                                   


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!