PHP远程图片本地化保存-curl方式
使用了composer包
"php-curl-class/php-curl-class": "^8.6",
大家需要自行下载并集成一下
/**
* 下载远程图片到本地
*
* @param string $txt 用户输入的文字,可能包含有图片的url
* @param string $keywords 网站域名关键字,路径中含有这个关键字的图片(即本网站图片)跳过
* @return string
*/
function getImageToLocal($txt,$keywords = 'qudong.com')
{
$matches = array();
preg_match_all('/<img.+?src=(.+?)\s/is',$txt,$matches);
if(!is_array($matches)) return $txt;
$curl = new \Curl\Curl();
$curl->setHeader('X-Requested-With', 'XMLHttpRequest');
foreach ($matches[1] as $k => $v)
{
$url = trim($v,"\"'");
if(strpos($url,$keywords) === false && substr($url,0,7) == 'http://') //非本站地址,需要下载图片
{
$data =$curl->get($url);
$file = APP_PATH."../public/remoteimg/". date('YmdHis') . rand(1,100) . $k . '.' . "jpg";
$start = strpos($file,"../public/remoteimg/");
$name = substr($file,$start);
$name = str_replace("..",request()->domain(),$name);
file_put_contents($file,$data);
if(is_file($file)) {
$txt = str_replace($v,$name,$txt);
}
}
}
return $txt;
}