PHP - XML: Removing Node


PHP XML Tips - Part 8: Do you want to remove child from exist XML? You can use removeChild(). Look at this:
<?php
$file = "books.xml";
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));


	   
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");

// original
echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";

// get document element
$root   = $xml->documentElement;
$fnode  = $root->firstChild;

//get a node
$ori    = $fnode->childNodes->item(1);

// remove
$fnode->removeChild($ori);

echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
?>

Books.xml, you can see at this.

Result, like this:



Series this article:
PHP - XML: Read from String
PHP - XML: Read from a File
PHP - XML: Retrieving Node Values
PHP - XML: Retrieving Attribute Values
PHP - XML: Processing XML
PHP - XML: Creating XML Document
PHP - XML: Adding XML Nodes
PHP - XML: Removing Node
PHP - XML: Replacing Node
PHP - XML: Filtering XML Nodes with XPath
PHP - XML: Filtering XML Nodes by Namespace

Bookmark and Share Tag: xml, node Category: PHP Basic Post : March 23rd 2008 Read: 51,588

advertisements


blog comments powered by Disqus