我在这里搜索了其他一些帖子,但还没有找到完美的解决方案
如果我有以下布局
<html>
<div> <---- This one
<div> text </div>
<div> text </div>
</div>
<p> text </p>
<div> <---- This one
<div> text </div>
<div> text </div>
</div>
<p> text </p>
</html>
我如何只获得最高级别的div。 (注意:里面的两个div只是一个例子,可能只有一个,或者可能是5或6。
注意:与之相关的其余代码是使用Simple html dom,我需要使用它来处理它。
答案 0 :(得分:2)
一种可能性是使用XPath。它看起来如下所示:
<?php
$doc = new DOMDocument();
// one of the few cases where you may use error suppression
@$doc->loadHTML($yourHtml);
$xPath = new XPath($doc);
$nodes = $xPath->query('//html/div');
免责声明:我没有对此进行过测试,但它至少应该让你接近