PHP - Delete XML Element
Dave Morgan is correct in that DOM classes are more powerful, but in case you want to stick with SimpleXML, try using the unset() function on any node, and that node will be removed from the XML.
unset($simpleXMLDoc->node1->child1)
You can use the DOM classes in PHP. ( http://us3.php.net/manual/en/intro.dom.php ).
You will need to read the XML document into memory, use the DOM classes to do manipulation, and then you can save out the XML as needed (to http or to file).
DOMNode is an object in there that has remove features (to address your question).
It's a little more complicated than SimpleXML but once you get used to it, it's much more powerful
(semi-taken from a code example at php.net)
<?php
$doc = new DOMDocument;
$doc->load('theFile.xml');
$thedocument = $doc->documentElement;
//this gives you a list of the messages
$list = $thedocument->getElementsByTagName('message');
//figure out which ones you want -- assign it to a variable (ie: $nodeToRemove )
$nodeToRemove = null;
foreach ($list as $domElement){
$attrValue = $domElement->getAttribute('time');
if ($attrValue == 'VALUEYOUCAREABOUT') {
$nodeToRemove = $domElement; //will only remember last one- but this is just an example :)
}
}
//Now remove it.
if ($nodeToRemove != null)
$thedocument->removeChild($nodeToRemove);
echo $doc->saveXML();
?>
This should give you a little bit of an idea on how to remove the element. It will print out the XML without that node. If you wanted to send it to file, just write the string to file.
Please have a look at
- Remove a child with a specific attribute, in SimpleXML for PHP on SO
- Remove nodes in SimpleXMLElement