PHP 下载远程图片

原文:https://www.codecasts.com/blo...php

在使用 PHP 作简单的爬虫的时候,咱们常常会遇到须要下载远程图片的需求,因此下面来简单实现这个需求。curl

1.使用 curl

好比咱们有下面这两张图片:ide

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

第一步,咱们能够直接来使用最简单的代码实现:post

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.封装一个类

缕清思路以后,咱们能够将这个基本的功能封装到一个类中:this

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

在者,咱们还能够这样稍微优化一下:url

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

封装成类以后,咱们能够这样调用代码来下载图片:code

$spider = new Spider();

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

这样,对付基本的远程图片下载就OK了。blog

相关文章
相关标签/搜索