php - 是否可以从 php 中的 htmlentities() 函数中提取 Dom 元素?
问题描述
感谢您花时间尝试帮助我解决我的问题。所以我正在做的是从一个链接尝试一个 html 解析器。因此,我首先使用 curl 链接到网站,然后将其转换为 htmlentities(),因此它不会加载到页面上,因此我从中获取了一个字符串,然后我使用 DOM 对象从中提取标签。我在谷歌搜索上检查了解析器的不同方法,所以我了解了一点,然后我执行了我的脚本,但问题是字符串被保存为 textCont 而不是真正的 html 文档,所以我想知道如何将 htmlentities 字符串转换为真正的 dom 文档并从中提取元素? var_dump 的图像在 这里是我的脚本:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://www.usatoday.com/story/news/world/2021/02/17/dubai-princess-sheikha-latifa-says-she-hostage-after-flee-attempt/6778014002/?utm_source=feedblitz&utm_medium=FeedBlitzRss&utm_campaign=usatodaycomworld-topstories');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
$htmlentities = htmlentities($result);
// I added the code here
$htmlDom = new DOMDocument();
$htmlDom->loadHTML($htmlentities);
$htmlDom->preserveWhiteSpace = false;
$styles = $htmlDom->getElementsByTagName('style');
foreach ($styles as $style) {
$item = $style->getElementsByTagName('td');
//echo the values
echo '1: '.$item->item(0)->nodeValue.'<br />';
echo '2: '.$item->item(1)->nodeValue.'<br />';
echo '3: '.$item->item(2)->nodeValue;
}
编辑:
我在代码旁边添加的是:
$htmlentities = htmlentities($result);
$htmlentities = str_replace(""",'"', $htmlentities);
$htmlentities = str_replace("'","'", $htmlentities);
$htmlentities = str_replace("<","<", $htmlentities);
$htmlentities = str_replace(">",">", $htmlentities);
libxml_use_internal_errors(true);
$htmlDom = new DOMDocument();
$htmlDom->loadHTML($htmlentities);
libxml_clear_errors();
var_dump($htmlDom);
解决方案
推荐阅读
- java - org.springframework.web.client.HttpClientErrorException$BadRequest: 400 null for Multipart post request
- c# - 如何将数据从视图传输到控制器,然后再传输到另一个视图(MVC C#)?
- python - 如何将烧瓶应用程序打包到 pex 文件中?
- vhdl - 我可以在“进程”中使用“端口映射”吗?
- python - 如何以 ORC 格式将数据列表写入 S3
- xml - 通过解析文件夹中的 XML 文件重命名文件夹
- php - 切换以从 PHP 编辑 Mysql 数据
- linux - 错误:$pkgauxdir 不是目录:'@@HOMEBREW_CELLAR@@/libtool/2.4.6_2/share/libtool/build-aux'
- asp.net-core - 扩展 AspNetCore InputTextArea 组件以添加行
- javascript - JavaScript 问题,Celsius to Kelvin 不起作用