Search code examples
phpxmlrecursionnodes

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


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

I tried this code, but it did not work ...

$document->preserveWhiteSpace = false; 
$books = $xpath->query('piletilve_info/places');
//echo "4";

foreach ($books as $places) {
    while($places->hasChildNodes()) {
        $places->removeChild($places->childNodes->item(0));
    }

    $places->parentNode->removeChild($places);
}

Source XML to be processed:

<piletilve_info>
   <places>
      <place>
        ...
      </place>
   </places>
   <other node>
      ...
   </other node>
</piletilve_info>

In the actual data there are more nodes that aren't places, but for simplicity this example shows only a few.

I saw C# examples, but I do not manage to port code to PHP.

Clarification : in code snippet, the variable $books is just a holder for the queried list. The name has no meaning.


Solution

  • 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>