[英]PHP Simple HTML DOM Parser: get only the parent
im useing "PHP Simple HTML DOM Parser" for this HTML: 我为此HTML使用“ PHP简单HTML DOM解析器”:
<ul id="menu-test-header" class="nav-menu">
<li>
<a href="">Test</a>
<ul class="sub-menu">
<li>
<a href="">sub test</a>
<a href="">sub test</a>
<a href="">sub test</a>
</li>
</ul>
</li>
<li>
<a href="">Test</a>
</li>
<li>
<a href="">Test</a>
<ul class="sub-menu">
<li>
<a href="">sub test</a>
</li>
</ul>
</li>
</ul>
I want to get in the end of the result only the parent "li a" without the "sub-menu" part. 我只想在结果的末尾获得父项“ li a”,而没有“子菜单”部分。 Its mean, in the end result should be only "Test" not "sub test". 它的意思是,最终结果应该只是“测试”而不是“子测试”。 What should be the selector? 选择器应该是什么?
PHP code: PHP代码:
foreach($html->find(".header-main .nav-menu li > a") as $menu) {
echo $menu->plaintext;
}
Thank you all, And sorry for my bad English :-) 谢谢大家,对不起我的英语不好:-)
As an alternative, you could point out the first <li>
children from the main <ul>
first, and from there, target each <a>
as ->children(0)
. 或者,您可以首先从主<ul>
指出第一个<li>
子级,然后从那里将每个<a>
目标定位为->children(0)
。
foreach($html->find('ul#menu-test-header', 0)->children() as $li) {
echo $li->children(0);
}
Sidenote: But I'd really suggest DOMDocument
+ DOMXpath
over simple-html-dom
: 旁注:但我真的建议DOMDocument
+ DOMXpath
不是simple-html-dom
:
$dom = new DOMDocument;
$dom->loadHTML($html_string);
$xpath = new DOMXpath($dom);
$first_list_links = $xpath->evaluate('//ul[@id="menu-test-header"]/li/a');
foreach($first_list_links as $links) {
echo $dom->saveHTML($links);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.