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中数组转换为SimpleXML教程

SimpleXML扩展函数提供了将XML转换为对象的工具集。这些对象处理普通的属性选择器和数组迭代器。 示例1: <?php // 将php数组转换为xml文档的代码...

一些php项目中比较通用的php自建函数的详解

以下一些php函数是我们it动力最常用的项目开发函数,这些函数还算是在比较多的项目中使用到的,也是比较通用的。1.请求接口的处理函数复制代码 代码如下:/**  * curl访...

PHP7内核CGI与FastCGI详解

PHP7内核CGI与FastCGI详解

CGI:是 Web Server 与 Web Application 之间数据交换的一种协议。 FastCGI:同 CGI,是一种通信协议,但比 CGI 在效率上做了一些优化。 PHP-...

PHP实现的浏览器检查类

本文实例讲述了PHP实现的浏览器检查类。分享给大家供大家参考,具体如下: <?php //原作者:epsilon7 //SonyMusic([email]sonymus...

使ecshop模板中可引用常量的实现方法

比如$smarty.const.'常量',这个就不能用。 其实模板引擎原理上并不复杂,只是把一些模板标签替换为php中的函数,变量,语法结构罢了。 这次要在ecshop模板中加入引用常量...