最近一直很忙,遇到一个手工活,需要下载一些远程的图片,一共一百多张,如果通过手工一张一张的保存,也太耗费时间了,于是上网google了一把,找到PHP批量下载图片文件的方法,原文是出自平凡世界博客的一片关于如何使用PHP批量下载CSS文件中的图片的文章,经过研究改写了一下就可以使用了,方便快捷多了.
PHP批量下载图片文件代码:
1 2 3 4 5 6 7 8 9 | set_time_limit(0);
$imagesURLArray = array_unique ( $imagesURLArray );
foreach ( $imagesURLArray as $imagesURL ) {
echo $imagesURL ;
echo "
";
file_put_contents ( basename ( $imagesURL ), file_get_contents ( $imagesURL ));
}
|
Copy after login
原理很简单,通过一个含有图片地址的数组循环,然后使用PHP的file_get_contents函数取得图片,在使用file_put_contents函数把图片保存下来.
注意:一定要加上设置PHP超时时间.
附上原文中通过php下载css中图片的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php
set_time_limit(0);
$styleFileContent = file_get_contents ('images/style.css');
preg_match_all( "/url((http://pic2.phprm.com/2014/07/01/" , $styleFileContent , $imagesURLArray .jpg);
$imagesURLArray = array_unique ( $imagesURLArray [1]);
foreach ( $imagesURLArray as $imagesURL ) {
file_put_contents ( basename ( $imagesURL ), file_get_contents ( $imagesURL ));
}
|
Copy after login
后来又找到一个php批量下载图片文件,假如现在我现在发现一个网站上的图片保存方式是1001 – 1999目录下都存放着从1开始(数量不等)的.jpg图片,现在我决定用php的方法将图片按照自己需要的样式直接下载到本地.
假如图片开始地址为:http://image.phprm.com/img/1001/1.jpg
这时我将1001处放到变量$id,1.jpg放到变量$num.jpg,保存的文件名为$id_$num.jpg,首先确保在此文件执行目录下面建一个名为img的并且可写的文件夹,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $id = isset( $_GET ['id']) && intval ( $_GET ['id']) && $_GET ['id']>1000 ? $_GET ['id'] : 1001;
$num = isset( $_GET ['num']) && intval ( $_GET ['num']) ? $_GET ['num'] : 1;
$url = "http://image.xxx.com/img/{$id}/{$num}.jpg" ;
$array =get_headers( $url ,1);
if (preg_match('/200/', $array [0])){
$new_url = "?id={$id}&num=" .( $num +1);
ob_start();
readfile( $url );
$img = ob_get_contents();
ob_end_clean();
$filename = "./img/{$id}_{$num}.jpg" ;
$f = fopen ( $filename ,'a');
fwrite( $f , $img );
fclose( $f );
} else {
$new_url = "?id=" .( $id +1). "&num=1" ;
}
if ( $id > 1999) exit ('全部完成');
echo $url ,' - ', $array [0],'<script>location.href= "'.$new_url.'" ;</script>';
|
Copy after login