通过DOMDocument获取具有子节点的节点的内容 [英] Getting content of the node having childs via DOMDocument
本文介绍了通过DOMDocument获取具有子节点的节点的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下html:
<html ><body >Body text <div >div content</div></body></html>
我如何在不嵌套<div>
的情况下获取正文内容?
我需要获取正文",但不知道如何执行此操作.
How could I get content of body without nested <div>
?
I need to get 'Body text', but do not have a clue how to do this.
运行结果
$domhtml = DOMDocument::loadHTML($html);
print $domhtml->getElementsByTagName('body')->item(0)->nodeValue;
是正文textdiv内容",这不完全是我想要得到的
is 'Body textdiv content', which is not exactly what I want to get
推荐答案
我更喜欢 DOMXPath 用于解决此类问题.非常灵活
I prefer DOMXPath for problems like this. It's very flexible
$domhtml = DOMDocument::loadHTML($html);
$xpath = new DOMXPath($domhtml);
$query="/html/body/text()"; //gets all text nodes that are direct children of body
$txtnodes = $xpath->query($query);
foreach ($txtnodes as $txt) {
echo $txt->nodeValue;
}
这篇关于通过DOMDocument获取具有子节点的节点的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文