PHP XPath子Concat和换行问题 [英] PHP XPath Child Concat And New Line Issues
问题描述
我正在使用DOMXPath查询要提取内容的HTML文档中的节点。
I am using DOMXPath to query nodes in an HTML document which content I would like to extract.
我有以下HTML文档:
I have the following HTML document:
<p class="data">
Immediate Text
<br>
Text In Second Line
<br>
E-Mail:
<script>Some Script Tag</script>
<a href="#">
<script>Another Script Tag</script>
Some Link In Third Line
</a>
<br>
Text In Last Line
</p>
我想收到以下结果:
第二行中的即时文本\r\nText电子邮件:第三行中的某些链接\最后一行中的r\nText
Immediate Text\r\nText In Second Line\r\nE-Mail: Some Link In Third Line\r\nText In Last Line
到目前为止,我有以下PHP代码:
So far I have the following PHP code:
#...
libxml_use_internal_errors(true);
$dom = new \DOMDocument();
if(!$dom->loadHTML($html)) {
#...
}
$xpath = \DOMXPath($dom);
$result = $xpath->query("(//p[@class='data'])[1]/text()[not(parent::script)]");
问题:
- 它不包括子节点的文本。
- 不包括换行符。
推荐答案
通过在 / text()
中使用子轴 /
您将仅获得当前节点上下文的直接子代。要获取所有后代,请改用后代轴( //
)。
By using child axis /
in /text()
you'll get only direct child of current node context. To get all descendants, use descendant axis (//
) instead.
同时获取文本节点和< br>
,您可以尝试使用 // nodes()
轴并按 node的类型进一步过滤-获取文本节点类型的节点-或 name -获取名为 br
-的元素:
To get both text node and <br>
, you can try using //nodes()
axis and filter further by node's type -to get nodes of type text node- or name -to get elements named br
- :
(//p[@class='data'])[1]//nodes()[self::text() or self:br][not(parent::script)]
这篇关于PHP XPath子Concat和换行问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!