php - xpath php - LIBXML_HTML_NOIMPLIED 的问题
问题描述
我正在尝试在文档中查找所有 p 标签,如下所示:
$dom = new DOMDocument();
$html = '<p>First</p><p>Second</p><p>Third</p><h3>Test 2</h3><p>Fourth</p>';
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$itens = [];
$xp = new DOMXPath($dom);
$res = $xp->query('//p');
foreach ($res as $item) {
$itens[] = $item->nodeValue;
}
print_r($itens);
但是当 LIBXML_HTML_NOIMPLIED 打开时,它不能按预期工作。我得到:
Array
(
[0] => FirstSecondThirdTest 2Fourth
[1] => Second
[2] => Third
[3] => Fourth
)
但我希望:
Array
(
[0] => First
[1] => Second
[2] => Third
[3] => Fourth
)
这里发生了什么?
解决方案
问题是您的 HTML 实际上是一个文档片段,因为它没有单个根节点。 loadHTML()
试图解决这个问题,你可以看看你是否这样做
echo $dom->saveHTML();
你得到
<p>First<p>Second</p><p>Third</p><h3>Test 2</h3><p>Fourth</p></p>
一个简单的解决方法是<div>
在加载之前向源添加一个基本标签(我使用 a )......
$dom->loadHTML("<div>$html</div>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
这使....
Array
(
[0] => First
[1] => Second
[2] => Third
[3] => Fourth
)
推荐阅读
- php - 登录不起作用,但没有给出任何错误
- html - 如何创建淡入/淡出图像动画
- excel - 在 Excel“不可读的内容”中查找错误的公式
- wagtail - 将 HTML 查看添加到 Wagtail 上的 Draftail 编辑器
- python - Python - “字符串索引必须是整数”错误使用 json 和 twitter
- sql-server - 从 T-SQL 脚本中调用 T-SQL 命令的 *File*
- python-3.x - Bs4和python中的问题
- java - 将 MapboxMap 从一个活动发送到另一个活动
- database - 使用 TypeORM Cordova 数据库将图像保存为 Blob
- javascript - 仅在输入按钮的值发生更改后,使用 JavaScript 和 jQuery 更改警报框中的字符串