1. 程式人生 > >解析html中連結url,並下載在指定目錄

解析html中連結url,並下載在指定目錄

<?php 
	$imgurls = array();
	$imgurls = self::getImgs($value['content']);
	if(is_array($imgurls)){
	foreach($imgurls as $imgurl)
	{
	 $pathes = parse_url($imgurl);
	 $path = $pathes['path'];
	 $dir = substr($path,0,strrpos($path,"/"));
	 $filename = substr($path,strrpos($path,"/")+1);
	 self::GrabImage($imgurl,$dir,$filename);
	}
	}

	function getImgs($content,$order='ALL'){
		$pattern="/((http|https|ftp|telnet|news):\/\/[a-z0-9\/\-_+=.~!%@?#%&;:$\\()|]+\.(jpg|gif|png|bmp|swf|rar|zip))/isU";
		preg_match_all($pattern,$content,$match);
		if(isset($match[1])&&!empty($match[1])){
			if($order==='ALL'){
				return $match[1];
			}
			if(is_numeric($order)&&isset($match[1][$order])){
				return $match[1][$order];
			}
		}
		return '';
	  }

	/*
	 *@$url string 遠端圖片地址
	 *@$dir string 目錄,可選 ,預設當前目錄(相對路徑)
	 *@$filename string 新檔名,可選
	 */
	function GrabImage($url, $dir='', $filename=''){
		if(empty($url)){
			return false;
		}
		//判斷目錄存在否,存在給出提示,不存在則建立目錄
		if (!is_dir($dir)){
			//第三個引數是“true”表示能建立多級目錄,iconv防止中文目錄亂碼
			$res=mkdir(iconv("UTF-8", "GBK", $dir),0777,true);
		}
		$filename = $dir ."/". $filename;
		if(!file_exists($filename))
		{
		  $content = file_get_contents($url);
		  file_put_contents($filename, $content);
		}

		return $filename; 
	}
?>