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

前端 未结 2 821
南旧
南旧 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();
    
    0 讨论(0)
  • 2020-12-12 01:35

    Goal is to delete whole node leaving other nodes ( in actual there are more, but for simplicity this example shows all

    $dom = new DOMDocument;
    $dom->load('places.xml');
    foreach ($dom->getElementsByTagName('places') as $places)
    {
        $places->parentNode->removeChild($places);
    }
    echo $dom->saveXml();
    

    will remove all <places> elements anywhere in the document, including any children.

    Output:

    <?xml version="1.0"?>
    <piletilve_info>
    
       <other>
          ...
       </other>
    </piletilve_info>
    
    0 讨论(0)
提交回复
热议问题