PHP远程采集正则图片案例
5328
很多时候我们需要采集其他网站的图片到本地,主要是为了稳定性,以及方便管理。下面提供一段代码。大家参考!
<?php
//图片接口地址(这里还是要拿小诗梦开刀)
$url = 'https://******/';
// 图片存放文件夹
$path = 'images/';
$str = file_get_contents($url);
preg_match_all('/<img alt="\/\/(.*?)" src="\/\/(.*?)" \/>/',$str,$img);
$imgUrl = 'https://'.$img[2][0];
if(!$imgUrl){
exit(json_encode(array('error'=>'采集失败')));
}
$filename = basename($imgUrl);
$filenames = $path.$filename;
if(file_exists($filenames)){
//文件已经存在
echo json_encode(array('url'=>$imgUrl,'filename'=>$filenames,'state'=>'202'));
}else{
if(download($imgUrl,$path)){
//采集成功
echo json_encode(array('url'=>$imgUrl,'filename'=>$filenames,'state'=>'200'));
}else{
//采集失败
echo json_encode(array('url'=>$imgUrl,'filename'=>$filenames,'state'=>'201'));
}
}
function download($url, $path = 'images/')
{
//远程下载保存
if (! file_exists ( $path )) {
mkdir ( "$path", 0777, true );
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
$filename = pathinfo($url, PATHINFO_BASENAME);
$resource = fopen($path . $filename, 'a');
fwrite($resource, $file);
fclose($resource);
return true;
}
?>本文网址:https://www.zztuku.com/detail-7619.html
站长图库 - PHP远程采集正则图片案例
申明:如有侵犯,请 联系我们 删除。








您还没有登录,请 登录 后发表评论!
提示:请勿发布广告垃圾评论,否则封号处理!!