当前位置:首页 > PHP教程 > php图像处理 > 列表

php采集内容中带有图片地址的远程图片并保存的方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-05 18:38:37 浏览: 评论:0 

这篇文章主要介绍了php采集内容中带有图片地址的远程图片并保存的方法,可实现采集并保存远程图片的功能,是非常实用的技巧,需要的朋友可以参考下

本文实例讲述了php采集内容中带有图片地址的远程图片并保存的方法,分享给大家供大家参考。具体实现方法如下:

  1. function my_file_get_contents($url, $timeout=30) { 
  2.  if ( function_exists('curl_init') )  
  3.  { 
  4.   $ch = curl_init(); 
  5.   curl_setopt ($ch, curlopt_url, $url); 
  6.   curl_setopt ($ch, curlopt_returntransfer, 1); 
  7.   curl_setopt ($ch, curlopt_connecttimeout, $timeout); 
  8.   $file_contents = curl_exec($ch); 
  9.   curl_close($ch); 
  10.  }  
  11.  else if ( ini_get('allow_url_fopen') == 1 || strtolower(ini_get('allow_url_fopen')) == 'on' )    
  12.  { 
  13.   $file_contents = @file_get_contents($url); 
  14.  }  
  15.  else  
  16.  { 
  17.   $file_contents = ''; 
  18.  } 
  19.  return $file_contents; 
  20. } 
  21.   
  22. function get_remote($body,$title){ 
  23.  
  24.  $img_array = array();  
  25.  $img_path = realpath("../../../upfile/news/").'/'.date("y/m/d/"); //采集远程图片保存地址 
  26.  //die($img_path); 
  27.  $img_rpath='/upfile/news/'.date("y/m/d/");  //设置访问地址 
  28.  $body = stripslashes(strtolower($body));  
  29.  preg_match_all("/(src|src)=["|'| ]{0,}(http://(.*).(gif|jpg|jpeg|png))/isu",$body,$img_array);  
  30.  $img_array = array_unique($img_array[2]);  
  31.  foreach ($img_array as $key => $value) {  
  32.   $get_file = my_file_get_contents($value,60); 
  33.   $filetime = time();    
  34.   $filename = date("ymdhis",$filetime).rand(1,999).'.'.substr($value,-3,3);  
  35.   if(emptyempty($get_file)){ 
  36.    @sleep(10); 
  37.    $get_file = my_file_get_contents($value,30); 
  38.    if(emptyempty($get_file)){ 
  39.     $body = preg_replace("/".addcslashes($value,"/")."/isu", '/notfound.jpg', $body); 
  40.     continue; 
  41.     } 
  42.   } 
  43.   if(!emptyempty($get_file) ){ 
  44.    if( mkdirs($img_path) ) 
  45.    { 
  46.     $fp = fopen($img_path.$filename,"w"); 
  47.     if(fwrite($fp,$get_file)){          
  48.      $body = preg_replace("/".addcslashes($value,"/")."/isu", $img_rpath.$filename, $body);  
  49.     } 
  50.     fclose($fp); 
  51.     @sleep(6); 
  52.    }    
  53.   }     
  54.  
  55.  } 
  56.  $body =str_replace("<img","<img ",$body);  
  57.  return $body; 
  58.  
  59. } 
  60.  
  61. function mkdirs($dir) 
  62. { 
  63.  if(!is_dir($dir)){ 
  64.   if(!mkdirs(dirname($dir))){ 
  65.    return false;} 
  66.   if(!mkdir($dir,0777)){ 
  67.    return false;} 
  68.  } 
  69.  return true; 
  70. } 
  71. //用法如下: 
  72.  
  73. $str ='fasfsdafsa<img src=http://filesimg.xxxx.com/2010/03/2010062300391582.jpg />'; 
  74. echo get_remote($str,'图片');

Tags: php采集远程图片

分享到: