gongzhonghao.png
扫码关注我们
最新赞助活动温馨提示:自愿赞助服务器费用,学生和没有工作的整站资源免费下载!
头像

php中实现下载远程图片保存到本地的方法实例详解

来源:http://erdangjiade.com/topic/2285.html 你好,世界。 2017-09-25 22:42浏览(9)

本篇文章主要介绍了PHP实现下载远程图片的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

1.使用 curl

比如我们有下面这两张图片:

$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'
];

第一步,我们可以直接来使用最简单的代码实现:

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);
}

那在下载远程图片的时候就可以这样:

foreach ( $images as $url ) {
  download($url);
}

2.封装一个类

缕清思路之后,我们可以将这个基本的功能封装到一个类中:

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);
  }
}

在者,我们还可以这样稍微优化一下:

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);
  }

封装成类之后,我们可以这样调用代码来下载图片:

$spider = new Spider();

foreach ( $images as $url ) {
  $spider->downloadImage($url);
}

以上就是php中实现下载远程图片保存到本地的方法实例详解的详细内容,更多请关注二当家的素材网其它相关文章!

评论0
头像

友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群

1 2