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.
Why stop there? It's also possible to pair the dynamically-built XML document in the previous example with an XSLT stylesheet to produce HTML output. Here's the stylesheet,
and here's a variant of the previous example which, instead of writing the XML
to a file, passes it through PHP's XSLT processor to produce an HTML page containing the data from the MySQL database.
<?php
// include class
include("Tree.php");
// set XSLT file
$xslt_file
= "addressbook.xsl";
// instantiate object
$tree = new XML_Tree();
// add
the
root element
$root =& $tree->addRoot("addressbook");
// open connection
to
database
$connection = mysql_connect("localhost", "joe", "secret") or die
("Unable
to
connect!");
// select database
mysql_select_db("db567") or die
("Unable
to
select database!");
// execute query
$query = "SELECT * FROM addressbook";
$result
= mysql_query($query) or die ("Error in query: $query. " .
mysql_error());
//
iterate through rows and print column data
while ($row = mysql_fetch_array($result))
{
//
add child elements
$item =& $root->addChild("item", NULL, array("id" =>
$row['id']));
$name
=& $item->addChild("name", $row['name']);
$address
=& $item->addChild("address",
$row['address']);
$tel =& $item->addChild("tel",
$row['tel']);
$fax =&
$item->addChild("fax", $row['fax']);
}
// close
database connection
mysql_close($connection);
//
read XML into string
$xml
=
$tree->get();
// create the XSLT processor
$xslt_processor
= xslt_create();
//
read in the data
$xslt = join("", file($xslt_file));
//
set up buffers
$arg_buffer
= array("/xml" => $xml, "/xslt" => $xslt);
// create
the XSLT processor
$xp
= xslt_create() or die("Could not create XSLT processor");
//
process the two
strings to get the desired output
if($result = xslt_process($xp,
"arg:/xml",
"arg:/xslt", NULL, $arg_buffer))
{
echo $result;
}
else
{
echo "An
error occurred: " . xslt_error($xp) . "(error code " .
xslt_errno($xp)
. ")";
}
//
free the resources occupied by the handler
xslt_free($xp);
?>