PHP批量下载html与css中图片文件实例
在php中要下载图片的第一步我需要利用正则来采集字符串中的图片地址,然后再利用php相关函数把图片直接读取并保存到本地服务器即实现了图片批量下载了。
最近一直很忙,遇到一个手工活,需要下载一些远程的图片,一共一百多张,如果通过手工一张一张的保存,也太耗费时间了,于是上网google了一把,找到PHP批量下载图片文件的方法,原文是出自平凡世界博客的一片关于如何使用PHP批量下载CSS文件中的图片的文章。经过研究改写了一下就可以使用了,方便快捷多了。
PHP批量下载图片文件代码:
<?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函数把图片保存下来。
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));
}
?>后来又找到一个php批量下载图片文件
假如现在我现在发现一个网站上的图片保存方式是1001 – 1999目录下都存放着从1开始(数量不等)的.jpg图片,现在我决定用php的方法将图片按照自己需要的样式直接下载到本地
假如图片开始地址为:http://image.xxx.com/img/1001/1.jpg
这时我将1001处放到变量$id,1.jpg放到变量$num.jpg,保存的文件名为$id_$num.jpg
首先确保在此文件执行目录下面建一个名为img的并且可写的文件夹
<?php
$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="' . $new_url . '";</script>';
?> 永久地址:http://www.phprm.com/code/56196.html
转载随意~请带上教程地址吧^^