Removing a node from XML file

I want to check if a XML file contains a particular node
eg. <example> some text </example>

and if it has, I want to remove the node as well as text in between them. After that I want save it so that original file is replaced by the new one. I would be thankful if someone can suggest me how it can be done in Zend php?

Try this. Just replace the three variable values at the top of the file as appropriate. The content used in the book.xml file for this sample was taken from Sample XML File (books.xml).



<?php
$elementToRemove = 'publish_date';
$xmlFileToLoad   = __DIR__ . '/book.xml';
$xmlFileToSave   = __DIR__ . '/book-modified.xml';

$dom = new DOMDocument();
$dom->load($xmlFileToLoad);

$matchingElements = $dom->getElementsByTagName($elementToRemove);
$totalMatches     = $matchingElements->length;

$elementsToDelete = array();
for ($i = 0; $i < $totalMatches; $i++){
    $elementsToDelete[] = $matchingElements->item($i);
}

foreach ( $elementsToDelete as $elementToDelete ) {
    $elementToDelete->parentNode->removeChild($elementToDelete);
}

$dom->save($xmlFileToSave);

Looks like there are some unnecessary lines of code. Why do you need to create array of $elementsToDelete first and then loop over it to delete nodes?
You can just delete nodes from inside the first loop - just do the
$elementToDelete->parentNode->removeChild($elementToDelete);
instead of creating array.

One less loop, one less array to maintain.

Good question. Maybe I should have commented the code :slight_smile:

Your suggestion is how I first wrote it but after viewing the results not all of the intended nodes were removed. After reading the user comments on the PHP.net entry for the removeChild method, PHP: DOMNode::removeChild - Manual, I noticed comments referencing internal iterator issues. So I adapted it.