1. 程式人生 > >通過PHP批量下載圖片檔案

通過PHP批量下載圖片檔案

最近一直很忙,遇到一個手工活,需要下載一些遠端的圖片,一共一百多張,如果通過手工一張一張的儲存,也太耗費時間了,於是上網google了一把,找到PHP批量下載圖片檔案的方法,原文是出自平凡世界部落格的一片關於如何使用PHP批量下載CSS檔案中的圖片的文章。經過研究改寫了一下就可以使用了,方便快捷多了。

PHP批量下載圖片檔案程式碼:

set_time_limit(0);//設定PHP超時時間
$imagesURLArray = array_unique($imagesURLArray );
 
foreach($imagesURLArray as $imagesURL) {
    echo $imagesURL
; echo "<br/>"; file_put_contents(basename($imagesURL), file_get_contents($imagesURL)); }

原理很簡單,通過一個含有圖片地址的陣列迴圈,然後使用PHP的file_get_contents函式取得圖片,在使用file_put_contents函式把圖片儲存下來。
P.S:一定要加上設定PHP超時時間哦~!

附上原文中通過php下載css中圖片的程式碼:

< ?php
/*
More & Original PHP Framwork
Copyright (c) 2007 - 2008 IsMole Inc.
Author: kimi
Documentation: 下載樣式檔案中的圖片,水水專用扒皮工具
*/
  //note 設定PHP超時時間 set_time_limit(0);   //note 取得樣式檔案內容 $styleFileContent = file_get_contents('images/style.css');   //note 匹配出需要下載的URL地址 preg_match_all("/url/((.*)/)/", $styleFileContent, $imagesURLArray);   //note 迴圈需要下載的地址,逐個下載 $imagesURLArray = array_unique($imagesURLArray[1]); foreach($imagesURLArray as
$imagesURL) { file_put_contents(basename($imagesURL), file_get_contents($imagesURL)); }