CHAPTER 8 – XML with PHP 5 – XML_Tree
Building an XML document with XML_Tree is quite easy, and can be done when the DOM XML extension is not available. You can install this PEAR class by typing pear install XML_Tree at your command prompt. To show you the difference between XML_Trees and the "normal" DOM XML method, we're going to build the same X(HT)ML document again. <?php require_once 'XML/Tree.php'; /* Create the document and the root node */ $dom = new XML_Tree; $html =& $dom->addRoot('html', '', array ( 'xmlns' => 'http://www.w3.org/1999/xhtml', 'xml:lang' => 'en', 'lang' => 'en' ) ); /* Create head and title elements */ $head =& $html->addChild('head'); $title =& $head->addChild('title', 'XML Example'); /* Create the body and p elements */ $body =& $html->addChild('body', '', array ('background' => 'bg.png')); $p =& $body->addChild('p'); /* Add the "Moved to" */ $p->addChild(NULL, "Moved to "); /* Add the a */ $p->addChild('a', 'example.org', array ('href' => 'http://example.org')); /* Add the ".", br and "foo & bar" */ $p->addChild(NULL, "."); $p->addChild('br'); $p->addChild(NULL, "foo & bar"); /* Dump the representation */ $dom->dump(); ?> As you can see, it's much easier to add an element with attributes and (simple) content with XML_Tree. For example, look at the following line that adds the a element to the p element: $p->addChild('a', 'example.org', array ('href' => 'http://example.org')); Instead of four method calls, you can add it with a one liner. Of course, the DOM XML extension has many more features than XML_Tree, but for sim- ple tasks, we recommend this excellent PEAR Class.