Functions to add, remove nodes from an XML file using PHP

Submitted by:Jhon Smith

Date added:08 April, 2012

Category:XML

Code example using PHP to add/ remove nodes from an XML file

Tags: add nodes , remove nodes

Code Snippet:

<?php
function removNode($myXML, $node, $attribute, $id) {
$xmlDoc = new DOMDocument();
$xmlDoc->load($myXML);
$xpath = new DOMXpath($xmlDoc);

if( $attribute!='' || $id!='' )
$nodeList = $xpath->query('//'.$node.'[@'.$attribute.'="'.$id.'"]');
else
$nodeList = $xpath->query('//'.$node.'');

if ($nodeList->length)
{
$node = $nodeList->item(0) ;
$node->parentNode->removeChild($node);
}
$xmlDoc->save($myXML) ;
}
?>
 
 

Comments