Building XML Trees With PHP - Spider, Spider On The Wall...
(Page 8 of 11 )
XMLTree doesn't just restrict you to XML elements - you can easily add attributes to any element as well, simply by specifying them as an associative array of name-value pairs in your calls to the addRoot() or addChild() methods. Here's an example,
<?php
// include class
include("XML/Tree.php");
// instantiate object
$tree
= new XML_Tree();
// add the root element
$root =& $tree->addRoot("superhero",
NULL, array("owner" => "Marvel
Comics"));
// 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();
?>
and here's the output:
<?xml version="1.0"?>
<superhero owner="Marvel Comics">
<name>Peter
Parker aka Spiderman</name>
<age>21</age>
<sex>male</sex>
<location>Manhattan</location>
</superhero>
This works with the addChild() method as well - here's an example,
<?php
// include class
include("XML/Tree.php");
// instantiate object
$tree
= new XML_Tree();
// add the root element
$root =& $tree->addRoot("superheroes");
//
add child elements
$name =& $root->addChild("member", "Spiderman", array("sex"
=> "male",
"location" => "Manhattan"));
$name =& $root->addChild("member",
"Superwoman", array("sex" => "female",
"location" => "Metropolis"));
$name =&
$root->addChild("member", "Batman", array("sex" => "male",
"location" => "Gotham
City"));
// print tree
$tree->dump();
?>
and here's the XML output.
<?xml version="1.0"?>
<superheroes>
<member sex="male" location="Manhattan">Spiderman</member>
<member sex="female" location="Metropolis">Superwoman</member>
<member
sex="male" location="Gotham City">Batman</member>
</superheroes>
Next: Making Friends And Influencing People >>
More PHP Articles
More By icarus, (c) Melonfire