php - 如何从 DOMDocument 中获取所有子节点?

标签 php domdocument child-nodes

我有以下内容

$string = '<html><head></head><body><ul id="mainmenu">
  <li id="1">Hallo</li>
  <li id="2">Welt
    <ul>
      <li id="3">Sub Hallo</li>
      <li id="4">Sub Welt</li>
    </ul>
  </li>
</ul></body></html>';
$dom = new DOMDocument;
$dom->loadHTML($string);

现在我想将所有 li ID 放在一个数组中。
我尝试了以下方法:

$all_li_ids = array();
$menu_nodes = $dom->getElementById('mainmenu')->childNodes;
foreach($menu_nodes as $li_node){
    if($li_node->nodeName=='li'){
        $all_li_ids[]=$li_node->getAttribute('id');         
    }
}
print_r($all_li_ids);

如您所见,这将打印出 [1,2]

我如何获得所有 child (子 child 以及 [1,2,3,4])?

最佳答案

我的测试没有通过使用 $dom->getElementById('mainmenu') 返回元素。但是如果你使用的话,不要使用 Xpath

$xpath = new DOMXPath($dom);
$ul = $xpath->query("//*[@id='mainmenu']")->item(0);

$all_li_ids = array();
// Find all inner li tags
$menu_nodes = $ul->getElementsByTagName('li');
foreach($menu_nodes as $li_node){
        $all_li_ids[]=$li_node->getAttribute('id');         
}
print_r($all_li_ids); 1,2,3,4

关于php - 如何从 DOMDocument 中获取所有子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37496876/

相关文章:

Javascript - 如何删除nodeName或HTML标签但保留内部标记?

Typescript:TextNode 的类型

typescript 子节点: `parentElement` and/or `parentNode` is null?

php - 添加时间(HH :MM) to <li> tags through jquery

php - 列计数与第 1 行错误的值计数不匹配

php - MYSQL查询神奇地抓取数值

php - fatal error : DOMDocument not found after Zend Server CE Update

php - 在 URL 中使用双引号

PHP GMAIL 使用 DOMDocument 和 cURL 接触 XML 解析

PHP遍历DOM并获取属性和文本