1.使用 curl

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


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




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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。


-----------------------------------------------------------------------------------------------

使用file_get_contents

function dlfile($file_url, $save_to)

{

 $content = file_get_contents($file_url);

 file_put_contents($save_to, $content);

}

使用CURL

function dlfile($file_url, $save_to)

{

 $ch = curl_init();

 curl_setopt($ch, CURLOPT_POST, 0);

 curl_setopt($ch,CURLOPT_URL,$file_url);

 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

 $file_content = curl_exec($ch);

 curl_close($ch);

 $downloaded_file = fopen($save_to, 'w');

 fwrite($downloaded_file, $file_content);

 fclose($downloaded_file);

}

使用fopen

function dlfile($file_url, $save_to)

{

 $infopen($file_url, "rb");

 $outfopen($save_to, "wb");

 while ($chunk = fread($in,8192))

 {

 fwrite($out, $chunk, 8192);

 }

 fclose($in);

 fclose($out);

}