xml remove child node in php

前端 未结 3 1043
无人共我
无人共我 2021-01-27 11:55

I\'m trying to remove the \"druzenje\" element by the \'id\' attribute. I know that for that to happen, i have to remove all the child nodes from that element.

&         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 12:34

    getElementsByTagName() returns "live" result that you remove the elements from the DOM. Copy it to an array to get a fixed list.

    $druzenja = iterator_to_array(
      $this->dom->getElementsByTagName('druzenje')
    );
    
    foreach ($druzenja as $node) {
      if ($node->getAttribute('id') == $id) {
        $node->parentNode->removeChild($node);
      }
    }
    

    Xpath would allow you to use more complex conditions. The result is not live.

    $xpath = new DOMXpath($this->dom);
    foreach ($xpath->evaluate('//druzenje[@id="'.$id.'"]') as $node) {
      $node->parentNode->removeChild($node);
    }
    

提交回复
热议问题