Building XML Trees With PHP - Anatomy Class (
Page 3 of 11 )
Let's
take a closer look at how I accomplished this.
1. The first step is, obviously, to include the XMLTree class
<?php
// include class
include("XML/Tree.php");
?>
You can either provide an absolute path to this file, or do what most lazy programmers
do - include the path to your PEAR installation in PHP's "include_path" variable,
so that you can access any of the PEAR classes without needing to type in long,
convoluted file paths.
2. Next, an object of the XMLTree class needs to be initialized, and assigned
to a PHP variable.
<?php
// instantiate object
$tree = new XML_Tree();
?>
This variable serves as the control point for future tree manipulation.
3. Every XML document must have a root element - which is where the addRoot()
method comes in.
<?php
// add the root element
$root =& $tree->addRoot("superhero");
?>
The addRoot() method is the starting point for your XML tree - it allows you
to specify the name and content of your document's root element, and returns a
Node object that can be used to graft further branches on to the document tree.
4. The Node object returned by the addRoot() method comes with methods of its
own - and one of the more useful ones is the addChild() method, which allows you
to add new children under that node. This method is fairly simple to use - all
it needs is the name of the child element to be added, and the content and attributes
(if any).
<?php
// add child elements
$name =& $root->addChild("name", "Peter Parker
aka Spiderman"); $age =&
$root->addChild("age", 21);
?>
Each call to addChild() returns another Node object, which in turn exposes an
addChild() method, thereby allowing you to add branches to the tree ad infinitum.
In this case, I've stopped at a two-level tree - but feel free to go as deep as
you like (the example on the next page demonstrates a more complex tree).
5. Once the tree is complete, you can do something useful with it - write it
to a file, pass it through a SAX parser or - as I've done here - simply output
it to the screen for all to admire.
<?php
// print tree
$tree->dump();
?>
The dump() method prints the entire XML document tree as is, and serves a very
useful purpose in debugging long or complex trees - I'll be using it fairly frequently
in the examples in this chapter.