Need to manipulate XML document trees, but don't have the DOM extension compiled into your PHP build? Take a look at XMLTree, a PEAR class that allows you to create and manipulate XML document trees without requiring the PHP DOM extension.
You've already seen that you can also add elements to an existing tree via the addChild() method. But XMLTree also allows you to prune an existing document tree, deleting elements from the hierarchy with the removeChild() method.
In order to illustrate this, consider the following example, which dynamically constructs a simple document tree:
<?php
// include class
include("XML/Tree.php");
// instantiate object
$tree
= new XML_Tree();
// add the root element
$root =& $tree->addRoot("superhero");
//
add child elements
$name =& $root->addChild("name", "Peter Parker aka Spiderman");
$age =&
$root->addChild("age", 21); $sex =& $root->addChild("sex", "male");
$location
=& $root->addChild("location", "Manhattan");
// print tree
$tree->dump();
?>
Now's let's suppose I wanted to remove the <age> element from the tree. With
removeChild(), it's a piece of cake:
<?php
// include class
include("XML/Tree.php");
// instantiate object
$tree
= new XML_Tree();
// add the root element
$root =& $tree->addRoot("superhero");
//
add child elements
$name =& $root->addChild("name", "Peter Parker aka Spiderman");
$age =&
$root->addChild("age", 21); $sex =& $root->addChild("sex", "male");
$location
=& $root->addChild("location", "Manhattan");
// remove second child node
(age)
$root->removeChild(1);
// print tree
$tree->dump();
?>
The removeChild() method takes, as argument, the index number of the child to
be removed under the specified Node object (remember that node numbering begins at 0, not 1). In this case, since I want to remove the <age> element, which is the second child of the root element, I can use