Heim  >  Artikel  >  Backend-Entwicklung  >  PHP采集远程图片的实例代码

PHP采集远程图片的实例代码

WBOY
WBOYOriginal
2016-07-25 08:55:37825Durchsuche
  1. function make_dir($path){
  2. if(!file_exists($path)){//不存在则建立
  3. $mk=@mkdir($path,0777); //权限
  4. @chmod($path,0777);
  5. }
  6. return true;
  7. }
复制代码

函数read_filetext()取得图片内容。 使用fopen打开图片文件,然后fread读取图片文件内容。

  1. function read_filetext($filepath){
  2. $filepath=trim($filepath);
  3. $htmlfp=@fopen($filepath,"r");
  4. //远程
  5. if(strstr($filepath,"://")){
  6. while($data=@fread($htmlfp,500000)){
  7. $string.=$data;
  8. }
  9. }
  10. //本地
  11. else{
  12. $string=@fread($htmlfp,@filesize($filepath));
  13. }
  14. @fclose($htmlfp);
  15. return $string;
  16. }
复制代码

函数write_filetext()写文件,将图片内容fputs写入文件中,即保存图片文件。

  1. function write_filetext($filepath,$string){
  2. //$string=stripSlashes($string);
  3. $fp=@fopen($filepath,"w");
  4. @fputs($fp,$string);
  5. @fclose($fp);
  6. }
复制代码

函数get_filename()获取图片名称,也可以自定义要保存的文件名。

  1. function get_filename($filepath){
  2. $fr=explode("/",$filepath);
  3. $count=count($fr)-1;
  4. return $fr[$count];
  5. }
复制代码

然后,将几个函数组合,在函数save_pic()中调用,最后返回保存后的图片路径。

  1. function save_pic($url,$savepath=''){
  2. //处理地址
  3. $url=trim($url);
  4. $url=str_replace(" ","%20",$url);
  5. //读文件
  6. $string=read_filetext($url);
  7. if(empty($string)){
  8. echo '读取不了文件';exit;
  9. }
  10. //文件名
  11. $filename = get_filename($url);
  12. //存放目录
  13. make_dir($savepath); //建立存放目录
  14. //文件地址
  15. $filepath = $savepath.$filename;
  16. //写文件
  17. write_filetext($filepath,$string);
  18. return $filepath;
  19. }
复制代码

最后一步,调用save_pic()函数保存图片,使用以下代码做测试。

  1. //目标图片地址
  2. $pic = "http://img0.pconline.com.cn/pconline/1205/06/2776119_end1_thumb.jpg";
  3. //保存目录
  4. $savepath = "images/";
  5. echo save_pic($pic,$savepath);
复制代码

实际应用中,可能会采集某个站点的内容,比如产品信息,包括采集防盗链的图片保存到网站上服务器上。 这时可以使用正则匹配页面内容,将页面中相匹配的图片都找出来,然后分别下载到网站服务器上,完成图片的采集。

测试示例:

  1. function get_pic($cont,$path){
  2. $pattern_src = '//';
  3. $num = preg_match_all($pattern_src, $cont, $match_src);
  4. $pic_arr = $match_src[1]; //获得图片数组
  5. foreach ($pic_arr as $pic_item) { //循环取出每幅图的地址
  6. save_pic($pic_item,$path); //下载并保存图片
  7. echo "[OK]..!";
  8. }
  9. }
复制代码

然后,通过分析页面内容,将主体内容找出来,调用get_pic()实现图片的保存。

  1. //采集太平洋电脑网上一篇关于手机报道内容页的图片
  2. $url = "http://gz.pconline.com.cn/321/3215791.html";
  3. $content = file_get_contents($url);//获取网页内容
  4. $preg = '#
    (.*)
    #iUs';
  5. preg_match_all($preg, $content, $arr);
  6. $cont = $arr[1][0];
  7. get_pic($cont,'img/');
复制代码

以上代码笔者亲测,可以采集图片,但是还有些场景没考虑进去,比如目标网站做了302多次跳转的,目标网站做了多种防采集的,大家自行研究下吧。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn