PHP XML remove element and all children by name

前端 未结 2 1028
离开以前
离开以前 2020-12-06 23:39

I have an XML file structured as:


  
    
    
             


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 00:01

    This should do it:

    foreach ($featureddel as $node) {
        $node->parentNode->removeChild($node);
    }
    

    You're probably just forgetting that with both xPath and getElementsByTagName you get a list (DOMNodeList) of items. That object itself only has a property $length, which you can use to determine how many objects are on the list, and function item($index), which returns specified DOMNode from the list. DOMNodeList is also iteratable through foreach. So besides foreach like I wrote above you can also do:

    for ($i = 0; $i < $featureddel->length; $i++) {
        $temp = $featureddel->item($i); //avoid calling a function twice
        $temp->parentNode->removeChild($temp);
    }
    

    But foreach is usually more preferred.

提交回复
热议问题