Delete all elements of a certain type from an XML doc using PHP

前端 未结 2 830
南旧
南旧 2020-12-12 01:20

I have what should be an easy task: delete nodes and their descendants from an XML document, leaving other nodes.

I tried this code, but

2条回答
  •  渐次进展
    2020-12-12 01:34

    When I was using the accepted answer it wouldn't remove all occurrences of the tag. The foreach loop would skip over tags probably because foreach relies on the internal array pointer and changing it within the loop leads to unexpected behavior.

    A working solution that I've found looks like this.

    $dom = new DOMDocument;
    $dom->load('places.xml');
    $placesNodes = $dom->getElementsByTagName('places') 
    while ($placesNodes->length > 0) {
        $node = $placesNodes->item(0);
        $node->parentNode->removeChild($node);
    }
    echo $dom->saveXml();
    

提交回复
热议问题