Building XML Trees With PHP - Doing The Chameleon
(Page 10 of 11 )
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,
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template
match="/">
<html>
<head></head>
<body>
<table border="1">
<tr>
<td><b>Name</b></td>
<td><b>Address</b></td>
<td><b>Tel</b></td>
<td><b>Fax</b></td>
</tr>
<xsl:apply-templates/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="//addressbook/item">
<tr>
<td><xsl:value-of
select="name" /></td>
<td><xsl:value-of select="address" /></td>
<td><xsl:value-of
select="tel" /></td>
<td><xsl:value-of select="fax"
/></td>
</tr>
</xsl:template>
</xsl: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);
?>
Here's what the output looks like:
Simple when you know how!
Next: Linking Out >>
More PHP Articles
More By icarus, (c) Melonfire