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程序设计有所帮助。

相关文章

使用GROUP BY的时候如何统计记录条数 COUNT(*) DISTINCT

例如这样一个表,我想统计email和passwords都不相同的记录的条数 复制代码 代码如下: CREATE TABLE IF NOT EXISTS `test_users` ( `e...

PHP实现的函数重载功能示例

本文实例讲述了PHP实现的函数重载功能。分享给大家供大家参考,具体如下: 由于PHP是弱类型语言,因此函数的输入参数类型无法确定(可以使用类型暗示,但是类型暗示无法用在诸如整型,字符串之...

百度工程师讲PHP函数的实现原理及性能分析(三)

常用php函数实现及介绍 count count是我们经常用到的一个函数,其功能是返回一个数组的长度。 count这个函数,其复杂度是多少呢? 一种常见的说法是count函数会遍历整个数...

PHP对MongoDB[NoSQL]数据库的操作

一、MongoDB简介 MongoDB (名称来自"humongous") 是一个可扩展的、高性能、开源、模式自由、面向文档的数据库,集文档数据库、键值对存储和关系型数据库的优点于一身。...

php模板函数 正则实现代码

我看过phpcms、discuz的源码,所以可能就缺乏创新了,不过原理大都相通,只是细节处理可能稍微不同。 说正题,下面开始谈谈具体实现过程了。 1.首先要想好模板文件放在哪?转换后的p...