php 下载网页所有图片,php批量下载一个网页中的所有图片

示例:$url = 'http://www.baidu.com/';//要下载的网页

$body=file_get_contents($url);//取网页的内容

$reurlpath=substr($url,0,strrpos($url,"/")+1);//取请求的当前路径

dump(auto_save_image($body,$reurlpath));//下载网页中的所有图片

//下面是下网站采集时候用到的采集图片后替换图片地址

$s=str_replace('http://','',$url);

$url='http://'.substr($s,0,strpos($s,'/')+1);//取图片所在的主域名

$body1=file_get_contents(内容页地址);//取网页的内容;//取网页的内容

$reurlpath=substr($url,0,strrpos($url,"/")+1);//取请求的当前路径

$imgarr=auto_save_image($body1,$reurlpath,'/uploads');//下载网页中的所有图片

//利用下载完的图片信息把内容中的图片地址换掉

foreach($imgarr as $b){

$body1=str_replace($b['codepath'],$b['savefilepath'],$body1);

}

返回的数组信息array(8) {

["width"]=>

int(140)

["height"]=>

int(100)

["codepath"]=>

string(61) "data/attachment/block/95/95c8bfbf0b2355b59b92bda5851a882d.jpg"

["jueduipath"]=>

string(86) "http://www.xxxxx.com/data/attachment/block/95/95c8bfbf0b2355b59b92bda5851a882d.jpg"

["savefilepath"]=>

string(46) "/uploads/image/201308/20130827150819155419.jpg"

["filepath"]=>

string(60) "E:\root/uploads/image/201308/20130827150819155419.jpg"

["oldfilename"]=>

string(36) "95c8bfbf0b2355b59b92bda5851a882d.jpg"

["newfilename"]=>

string(24) "20130827150819155419.jpg"

}

下面是用到的函数/*

*@param $body 一段html文本

*@param $reurlpath 请求的url路径(http://www.baidu.com/)精确到目录后面要加上 '/'

*@param $filepath 保存文件的路径,默认为当前站点根目录中的uploads文件夹

*返回值是一个已经下载的图片信息的数组

*/

function auto_save_image($body, $reUrlPath, $filepath = '/uploads') {

//set_time_limit(1800);

//echo $body;

$img_array = array();

preg_match_all('/(src)=[\"|\'| ]{0,1}([^>]+\.(gif|jpg|jpeg|bmp|png))[\"|\'| ]{0,1}/i', $body, $img_array);

$img_array = array_unique($img_array[2]);

$imginfo   = array();

foreach ($img_array as $key => $value) {

$imginfo[] = downloadImage($reUrlPath, $value, $filepath);

}

return $imginfo;

}

function createFolder($path) {

if (!file_exists($path)) {

createFolder(dirname($path));

mkdir($path, 0700);

}

}

/**

* 下载远程图片

*@param string $host图片的主机域名 如http://www.baidu.com/ 带后面斜杠

* @param string $url 图片的绝对url

* @param string $filepath 文件的完整路径(包括目录,不包括后缀名,例如/www/images/test) ,此函数会自动根据图片url和http头信息确定图片的后缀名

* @return mixed 下载成功返回一个描述图片信息的数组,下载失败则返回false

*/

function downloadImage($host, $url, $filepath) {

$Yurl         = $url;

$milliSecond  = date('YmdHms') . strftime("%H%M%S", time()); //文件名

$Savefilepath = $filepath . "/image/" . date("Ym"); //文件保存路径

$filepath     = str_replace("\\", '/', $_SERVER['DOCUMENT_ROOT'] . $Savefilepath); //转化为当前网站目录

if (!file_exists($filepath)) {

createFolder($filepath);

}

//如果文件夹不存在就创建

$filepath = $filepath . "/" . $milliSecond; //加上文件名

if (strtolower(substr($url, 0, 4)) != 'http') {

if (substr($url, 0, 1) == '/') {

$url = substr($url, 1);

}

$url = $host . $url;

} else {

$url = $url;

}

//服务器返回的头信息

$responseHeaders = array();

//原始图片名

$originalfilename = '';

//图片的后缀名

$ext = '';

$ch  = curl_init($url);

//设置curl_exec返回的值包含Http头

curl_setopt($ch, CURLOPT_HEADER, 1);

//设置curl_exec返回的值包含Http内容

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//设置抓取跳转(http 301,302)后的页面

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

//设置最多的HTTP重定向的数量

curl_setopt($ch, CURLOPT_MAXREDIRS, 2);

//服务器返回的数据(包括http头信息和内容)

$html = curl_exec($ch);

//获取此次抓取的相关信息

$httpinfo = curl_getinfo($ch);

curl_close($ch);

if ($html !== false) {

//分离response的header和body,由于服务器可能使用了302跳转,所以此处需要将字符串分离为 2+跳转次数 个子串

$httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);

//倒数第二段是服务器最后一次response的http头

$header = $httpArr[count($httpArr) - 2];

//倒数第一段是服务器最后一次response的内容

$body = $httpArr[count($httpArr) - 1];

$header .= "\r\n";

//获取最后一次response的header信息

preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);

if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) {

for ($i = 0; $i 

if (array_key_exists($i, $matches[2])) {

$responseHeaders[$matches[1][$i]] = $matches[2][$i];

}

}

}

//获取图片后缀名

if (0 

$originalfilename = $matches[0];

$ext              = $matches[1];

} else {

if (array_key_exists('Content-Type', $responseHeaders)) {

if (0 

$ext = $extmatches[1];

}

}

}

//保存文件

if (!empty($ext)) {

$filepath .= ".$ext";

//如果目录不存在,则先要创建目录

createFolder(dirname($filepath));

$local_file = fopen($filepath, 'w');

if (false !== $local_file) {

if (false !== fwrite($local_file, $body)) {

fclose($local_file);

$sizeinfo = getimagesize($filepath);

return array(

'width'        => $sizeinfo[0],

'height'       => $sizeinfo[1],

'codepath'     => $Yurl, //源代码中文件的路径

'jueduipath'   => $url, //文件绝对路径

'savefilepath' => str_replace(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']), '', $filepath), //文件保存的相对路径

'filepath'     => $filepath,

'oldfilename'  => $originalfilename,

'newfilename'  => pathinfo($filepath, PATHINFO_BASENAME),

);

}

}

}

}

return false;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值