PHP利用 simple_html_dom 远程图片本地化
发表于:2024-10-31 17:42:19浏览:286次
废话少说,直接上代码
在控制器中引入 simple_html_dom 库
use voku\helper\HtmlDomParser;
定义获取指定页面的文章内容和图片本地化
一般用于网页内容爬取
/**
*@description 数据列表
*@buildcode(false)
*/
function getWebContent(){
// 获取远程网页内容
$url = 'http://www.news.cn/tech/20240520/f5652ab6026e48028e89234b7cd60eaa/c.html';
// 获取当前网页路径,用于图片获取
$parsedUrl = parse_url($url);
$path = $parsedUrl['path'];
$directoryPath = dirname($path);
$fullPathWithoutFileName = $parsedUrl['scheme']. '://'. $parsedUrl['host']. $directoryPath;
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$html = file_get_contents($url, false, stream_context_create($arrContextOptions));
$filename = 'ok.html';
file_put_contents($filename, $html);
$dom = HtmlDomParser::str_get_html($html);
$elements = $dom->find('div#detail');
// 查找图片
$images = $elements->find('img');
$localImg = [];
foreach ($images as $image) {
$remoteImageUrl = $image->src;
if (strpos($remoteImageUrl, 'http://') === 0 || strpos($remoteImageUrl, 'https://') === 0) {
$imgFile = $remoteImageUrl;
} else {
$imgFile = $fullPathWithoutFileName.'/'.$remoteImageUrl;
}
$localImg[] = $imgFile;
$localFileName = './backup/'. basename($remoteImageUrl);
// 获取远程图片内容
$imgContent = file_get_contents($imgFile);
file_put_contents($localFileName, $imgContent);
}
$data['content'] = $elements ->innerhtml[0];
$data['img'] = $localImg;
return $data;
$html->clear();
}
推荐文章
- 新闻APP源码,新闻门户网站开源系统ThinkPHP6框架UniAPP多端发布
- ThinkPHP6.0.3+ElementAdmin+UniAPP多端新闻网站、App 源码
- PHP使用Simple_html_dom采集网页内容采集网页内容和标题、图片等
- 谷歌浏览器输入地址后http自动转https解决方法
- centos7 服务器维护之查看最多流量访问IP地址,防止恶意访问IP
- PHPStorm快捷键大全,不断更新收藏中(熟练使用后基本上告别鼠标了!)
- 关于宝塔 负载和CPU到达100%,负载和CPU很高的优化方案
- [WDS] Disconnected解决方法
- uniapp+thinkphp6开发答题系统 API接口开发签名验证、接口安全验证方法
- 阿里云服务器如何利用安全组设置拦截IP(IP段)