Home  >  Article  >  php教程  >  PHP批量下载html与css中图片文件实例

PHP批量下载html与css中图片文件实例

WBOY
WBOYOriginal
2016-05-25 16:45:01825browse

最近一直很忙,遇到一个手工活,需要下载一些远程的图片,一共一百多张,如果通过手工一张一张的保存,也太耗费时间了,于是上网google了一把,找到PHP批量下载图片文件的方法,原文是出自平凡世界博客的一片关于如何使用PHP批量下载CSS文件中的图片的文章,经过研究改写了一下就可以使用了,方便快捷多了.

PHP批量下载图片文件代码:

set_time_limit(0);//设置PHP超时时间 
	$imagesURLArray = array_unique($imagesURLArray ); 
	 
	foreach($imagesURLArray as $imagesURL) { 
	    echo $imagesURL; 
	    echo " 
	"; 
	    file_put_contents(basename($imagesURL), file_get_contents($imagesURL)); 
	} 

原理很简单,通过一个含有图片地址的数组循环,然后使用PHP的file_get_contents函数取得图片,在使用file_put_contents函数把图片保存下来.

注意:一定要加上设置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(&#39;images/style.css&#39;); 
	 
	//note 匹配出需要下载的URL地址 
	preg_match_all("/url((http://pic2.phprm.com/2014/07/01/", $styleFileContent, $imagesURLArray.jpg); 
	 
	//note 循环需要下载的地址,逐个下载 
	$imagesURLArray = array_unique($imagesURLArray[1]); 
	    foreach($imagesURLArray as $imagesURL) { 
	    file_put_contents(basename($imagesURL), file_get_contents($imagesURL)); 
	} 
	 

后来又找到一个php批量下载图片文件,假如现在我现在发现一个网站上的图片保存方式是1001 – 1999目录下都存放着从1开始(数量不等)的.jpg图片,现在我决定用php的方法将图片按照自己需要的样式直接下载到本地.

假如图片开始地址为:http://image.phprm.com/img/1001/1.jpg

这时我将1001处放到变量$id,1.jpg放到变量$num.jpg,保存的文件名为$id_$num.jpg,首先确保在此文件执行目录下面建一个名为img的并且可写的文件夹,代码如下:

$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); 
	 
	//通过返回200和400来判断是增加$id或者$num 
	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="&#39;.$new_url.&#39;";</script>';  
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn