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

yipeiwu_com6年前PHP代码库

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

复制代码 代码如下:
function my_file_get_contents($url, $timeout=30) {
 if ( function_exists('curl_init') ) 
 {
  $ch = curl_init();
  curl_setopt ($ch, curlopt_url, $url);
  curl_setopt ($ch, curlopt_returntransfer, 1);
  curl_setopt ($ch, curlopt_connecttimeout, $timeout);
  $file_contents = curl_exec($ch);
  curl_close($ch);
 } 
 else if ( ini_get('allow_url_fopen') == 1 || strtolower(ini_get('allow_url_fopen')) == 'on' )   
 {
  $file_contents = @file_get_contents($url);
 } 
 else 
 {
  $file_contents = '';
 }
 return $file_contents;
}

 
复制代码 代码如下:
function get_remote($body,$title){
 
 $img_array = array(); 
 $img_path = realpath("../../../upfile/news/").'/'.date("y/m/d/"); //采集远程图片保存地址
 //die($img_path);
 $img_rpath='/upfile/news/'.date("y/m/d/");  //设置访问地址
 $body = stripslashes(strtolower($body)); 
 preg_match_all("/(src|src)=["|'| ]{0,}(http://(.*).(gif|jpg|jpeg|png))/isu",$body,$img_array); 
 $img_array = array_unique($img_array[2]); 
 foreach ($img_array as $key => $value) { 
  $get_file = my_file_get_contents($value,60);
  $filetime = time();   
  $filename = date("ymdhis",$filetime).rand(1,999).'.'.substr($value,-3,3); 
  if(emptyempty($get_file)){
   @sleep(10);
   $get_file = my_file_get_contents($value,30);
   if(emptyempty($get_file)){
    $body = preg_replace("/".addcslashes($value,"/")."/isu", '/notfound.jpg', $body);
    continue;
    }
  }
  if(!emptyempty($get_file) ){
   if( mkdirs($img_path) )
   {
    $fp = fopen($img_path.$filename,"w");
    if(fwrite($fp,$get_file)){         
     $body = preg_replace("/".addcslashes($value,"/")."/isu", $img_rpath.$filename, $body); 
    }
    fclose($fp);
    @sleep(6);
   }   
  }    
 
 }
 $body =str_replace("<img","<img ",$body); 
 return $body;
 
}
 
function mkdirs($dir)
{
 if(!is_dir($dir)){
  if(!mkdirs(dirname($dir))){
   return false;}
  if(!mkdir($dir,0777)){
   return false;}
 }
 return true;
}
//用法如下:
 
$str ='fasfsdafsa<img src=/zb_users/upload/202003/eu3eptk52mg.jpg />';
echo get_remote($str,'图片');

希望本文所述对大家的php程序设计有所帮助。

相关文章

php中二分法查找算法实例分析

本文实例讲述了php中二分法查找算法实现方法。分享给大家供大家参考,具体如下: 二分法查找在高级点的开发可能会用到了,当然在大公司找工作时都会有面试题是这种了,下面我们来看一篇关于二分法...

详解PHP的Yii框架中日志的相关配置及使用

详解PHP的Yii框架中日志的相关配置及使用

默认的日志是输出到protected/runtime/application.log 如果需要修改那么需要在main.php里面的 components 下面增加log配置,如下:...

国外PHP程序员的13个好习惯小结

也就是本文列举的这13个PHP编码好习惯,如果你有更好的建议,欢迎在本文后面的评论中发表,我这个人是喜欢求知的1、使用select从相同的数据库查询信息时,使用一个join语句一次性整齐...

PHP4和PHP5共存于一系统

PHP4和PHP5共存于一系统˂!-- google 的广告条 2005年09月20日换位置 唉,22号被停了.郁闷,没作弊呀 11.27日重开了 ˂!-- googl...

php 检查电子邮件函数(自写)

复制代码 代码如下: function is_valid_email_address($email){ $qtext = '[^//x0d//x22//x5c//x80-//xff]';...