PHP利用 simple_html_dom 远程图片本地化
发表于:2024-10-31 17:42:19浏览:1009次
废话少说,直接上代码
在控制器中引入 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();
}
推荐文章
- 微信小程序网络抽奖系统源码,H5在线有奖知识竞赛扫码制作
- TinyMCE version 6.0.1 粘贴稿件自动下载并上传远程图片的代码
- element-ui 表格组件el-table操作toggleRowSelection事件会主动触发selection-change的坑
- 如何关闭卸载360软件管家
- thinkphp6的自定义异常处理
- 新闻网站源码 网站群系统+精美wap手机端(包含数据)淘宝在售源码
- uniapp 项目中使用花生壳报错Invalid Host header时该如何处理
- 勾股DEV是一款专为IT研发团队打造的项目管理与团队协作的系统工具
- 谷歌浏览器输入地址后http自动转https解决方法
- 记者证查询地址