Building XML Trees With PHP - Rank And File
(Page 7 of 11 )
In addition to dynamically creating an XML document tree, XMLTree also allows you to read an existing tree into memory, via its getTreeFromFile() method. Consider the following XML file, named "me.xml":
<?xml version="1.0"?>
<me>
<name>John Doe</name>
<age>16</age>
<sex>male</sex>
</me>
Let's now read this into an XML document tree with the getTreeFromFile() method:
<?php
// include class
include("XML/Tree.php");
// instantiate object
$tree
= new XML_Tree("me.xml");
// read file contents
$root =& $tree->getTreeFromFile();
//
print tree
$tree->dump();
?>
In this case, the getTreeFromFile() method has been used to read the contents
of the XML file specified in the object constructor, and convert it into an XMLTree object. The tree can then be viewed via a call to dump().
Take a quick peek at the object created by getTreeFromFile() with the print_r() function, and here's what you'll see:
xml_tree_node Object
(
[attributes] => Array
(
)
[children]
=> Array
(
[0] => xml_tree_node Object
(
[attributes] => Array
(
)
[children] => Array
(
)
[content] => John Doe
[name] => name
)
[1] => xml_tree_node
Object
(
[attributes] => Array
(
)
[children] =>
Array
(
)
[content]
=> 16
[name] => age
)
[2] =>
xml_tree_node Object
(
[attributes]
=> Array
(
)
[children]
=> Array
(
)
[content] => male
[name] => sex
)
)
[content] =>
[name]
=>
me
)
As you can see, the XML document is converted into a series of nested arrays,
each one representing a node on the document tree.
Similar, though not identical, is the getTreeFromString() method, which converts an XML-compliant string into an XMLTree object. Take a look:
<?php
// include class
include("XML/Tree.php");
// instantiate object
$tree
= new XML_Tree();
// create string
$str = "<?xml version='1.0'?> <me>
<name>John
Doe</name> <age>16</age>
<sex>male</sex> </me>";
//
read string
into tree
$root =& $tree->getTreeFromString($str);
// print
tree
$tree->dump();
?>
Next: Spider, Spider On The Wall... >>
More PHP Articles
More By icarus, (c) Melonfire