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

yipeiwu_com5年前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面向对象五大原则之依赖倒置原则(DIP)详解

本文实例讲述了PHP面向对象五大原则之依赖倒置原则(DIP)。分享给大家供大家参考,具体如下: 什么是依赖倒置呢?简单地讲就是将依赖关系倒置为依赖接口,具体概念如下: 1.上层模块不应该...

php计算给定时间之前的函数用法实例

本文实例讲述了php计算给定时间之前的函数用法。分享给大家供大家参考。具体如下: 这里给定一个时间,计算这个时间在多久前,比如:2天前,1年前 <?php functi...

php使用array_search函数实现数组查找的方法

本文实例讲述了php使用array_search函数实现数组查找的方法。分享给大家供大家参考。具体实现方法如下: <?php $array = array(4,5,7,...

php中计算时间差的几种方法

一个简单的例子就是计算借书的天数,这需要php根据每天的日期进行计算,下面就来谈谈实现这种日期计算的几种方法: (1) 如果有数据库就很容易了!若是MSSQL可以使用触发器!用专门计算日...

比较简单的百度网盘文件直链PHP代码

百度网盘速度快,稳定性好,你值得拥有,如果以后支持直连以后就可以直接使用百度的网盘了。这里提供的是临时解决方案,不保证以后可以使用将下面的代码保存为downbd.php 复制代码 代码如...