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

来源:赵克立博客 分类: 工具分享 标签:小工具PHP数组PHP发布时间:2014-04-29 06:04:39最后更新:2019-05-28 13:30:50浏览:10767
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2019-05-28 13:30:50
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

   示例:

$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 < count($matches[1]); $i++) {
				if (array_key_exists($i, $matches[2])) {
					$responseHeaders[$matches[1][$i]] = $matches[2][$i];
				}
			}
		}
		//获取图片后缀名
		if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {
			$originalfilename = $matches[0];
			$ext              = $matches[1];
		} else {
			if (array_key_exists('Content-Type', $responseHeaders)) {
				if (0 < preg_match('{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) {
					$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;
}

微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python