获取一个网页内的远程图片,并自动保存到本地。
<?php
header("Content-Type: text/html; charset=utf-8");
error_reporting(E_ERROR|E_WARNING);
//全局配置
$fromFile = "aaa.css"; //要抓取的文件
$savePath = "ttttttttt"; //保存路径
$fromDomain = "http://www.xxx.com/"; //要抓取的域名
//读取css样式并且分离出所有image的url
$str = file_get_contents($fromFile);
$strArr = explode("url(",$str);
$i = 0;
foreach($strArr as $val){
$val1 = explode(")",$val);
if(strpos($val1[0],'jpg')||strpos($val1[0],'png')||strpos($val1[0],'gif'))
$imgUrl[$i++] = $val1[0];
}
//PS:上面可以用正则的,但是我觉得这样也不错
//开始抓取
foreach($imgUrl as $url){
if($url=="") continue;
$filename = $savePath.$url;
$url = $fromDomain.$url;
getImage($url,$filename);
}
function getImage($url,$filename){
ob_start();
$context = stream_context_create(
array (
'http' => array (
'follow_location' => false // don't follow redirects
)
)
);
//请确保php.ini中的fopen wrappers已经激活
readfile( $url,false,$context);
$img = ob_get_contents();
ob_end_clean();
$fp2 = @fopen($filename,"a");
fwrite($fp2,$img);
fclose($fp2);
echo $filename." ok √";
}
?>