本文介绍了如何使用PHP DOMDocument在一级获取节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是PHP DOM对象的新手,有一个问题我找不到解决方案。我有一个具有以下HTML的DOMDocument:
I'm new to PHP DOM object and have a problem I can't find a solution. I have a DOMDocument with following HTML:
<div id="header">
</div>
<div id="content">
<div id="sidebar">
</div>
<div id="info">
</div>
</div>
<div id="footer">
</div>
我需要获取第一级的所有节点(标题,内容,页脚)。 hasChildNodes()不起作用,因为第一级节点可能没有子节点(header,footer)。
现在我的代码看起来像:
I need to get all nodes that are on first level (header, content, footer). hasChildNodes() does not work, because first level node may not have children (header, footer).For now my code looks like:
$dom = new DOMDocument();
$dom -> preserveWhiteSpace = false;
$dom -> loadHTML($html);
$childs = $dom -> getElementsByTagName('div');
但这可以让我得到所有的div。任何建议?
But this gets me all div's. any advice?
推荐答案
您可能需要离开DOMDocument - 可能转换为SimpleXML或DOMXpath
You may have to go outside of DOMDocument - maybe convert to SimpleXML or DOMXpath
$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);
$xpath = new DOMXpath($doc);
$elements = $xpath->query("/");
这篇关于如何使用PHP DOMDocument在一级获取节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!