Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does php collect remote pictures with image addresses in the content and save them?

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

这篇文章主要讲解了"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("

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report