Home  >  Article  >  php教程  >  php实现图片远程采集

php实现图片远程采集

WBOY
WBOYOriginal
2016-06-08 17:30:151181browse
<script>ec(2);</script>

//本程序为初学者入门,你可以随意更改使用
//如有问题或有什么改进和优化,还望与我分享 QQ:297535861
//与你一块进步。
//2007-12-26
function str_substr($str ,$statr, $end) { //字符串截取函数
  $x = strpos($str, $statr);
  return substr($str,  $x+strlen($start), strpos($str, $end)-$x+strlen($end)); 
}
//////////////////////////////////////////////////
$url="[url=http://www.XXXXXXX.XXX/XXX]http://www.XXXXXXX.XXX/XXX";//[/url]给据采集内容自己定,这句上传后给自动加了连接,请去掉
$str=file_get_contents($url); ///file_get_contents -- 将整个文件读入一个字符串
$start='#######';//截取内容前的html  最后网页中唯一
$end='########';//截取内容后的html 最后网页中唯一
$content=str_substr($str , $start, $end);
//echo $content; //测试采集到的内容
echo '


';
///////////////////////////////////////////////////
$img_array = array();
$content1 = stripslashes($content); //stripslashes函数作用是去掉字符串中的转义字符
if (get_magic_quotes_gpc()) $content1 = stripslashes($content1);
//echo $content1;//文章内容嘿嘿开始处理了
preg_match_all("/(src|SRC)="(http://(.+)/(.+).(gif|jpg|jpeg|bmp|png))/isU",$content1,$img_array,PREG_PATTERN_ORDER);//正则开始匹配所有的图片并放入数组$img_array中 ,=匹配规则可根据具体情况改写,这个通用性不强,还望那位高手给个通吃的匹配=
$img_array = array_unique($img_array[2]); //array_unique -- 移除数组中重复的值,$img_array[2]到现在没有高清楚,猜想可能是取出二维数组中的某组。
//print_r($img_array); //测试匹配到的内容
set_time_limit(0); //限定最大执行时间

//开始保存匹配内容中图片,修改名称并保存的本地文件夹中
foreach ($img_array as $key => $value) { //使用循环语句把匹配到的数组内容(图片)进行一一处理
if(file_get_contents($value)) $get_file = file_get_contents($value);//开始获取图片了哦 使用file_get_contents得到文件
else dir("出错");
$filetime = time(); //得到时间戳
$filepath = "pic2/".date("Ym",$filetime)."/";//图片保存的路径目录
!is_dir($filepath) ? mkdir($filepath) : null;  //如果目录不存在,则创建目录,注意:要有相应的目录权限。
$filename = date("YmdHis",$filetime).rand(100,999).'.'.substr($value,-3,3); //生成文件名,rand(100,999)的作用是防止文件名重复
$fp = @fopen($filepath.$filename,"w"); //以写方式打开文件
@fwrite($fp,$get_file); //
fclose($fp);//完工,哈
$content1 = preg_replace("/".addcslashes($value,"/")."/isU", "pic2/".date("Ym",$filetime)."/".$filename, $content1);  //顺便替换一下文章里面的图片地址
echo $value.'=>'.'pic2/'.date('Ym',$filetime).'/'.$filename.'
';  //测试图片复制前后,路径是否正常。
}
echo '


';
echo $content1; //可把$content1存入数据库
?>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn