前面发的《远程采集接口图片案例》用过的都说好
小诗梦之后把图片放到了另外一个域名,而且图片方式有所变更,所以写了一个正则采集方式
<?php /** * 随机图片正则采集案例 * @author Youngxj <blog@youngxj.cn> * @url http://blog.youngxj.cn * @time 2018-09-20 */ //图片接口地址(这里还是要拿小诗梦开刀) $url = 'https://cdn.mom1.cn/'; // 图片存放文件夹 $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; } ?>
发表评论: