XSL Transformation With PHP And Sablotron - Start It Up
(Page 3 of 8 )
Let's start with a simple example. Consider the following XML document:
<?xml version="1.0"?>
<me>
<name>John Doe</name>
<address>94,
Main Street, Nowheresville 16463, XY</address>
<tel>738 2838</tel>
<email>johndoe@black.hole.com</email>
<url>http://www.unknown_and_unsung.com/</url>
</me>
Now, let's suppose that I need to transform this XML document into an HTML document
which looks like this:
Here's the XSLT stylesheet to accomplish this transformation:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
</head>
<body>
<h1>Contact information for
<b><xsl:value-of select="me/name" /></b></h1>
<h2>Mailing address:</h2>
<xsl:value-of select="me/address" />
<h2>Phone:</h2>
<xsl:value-of select="me/tel" />
<h2>Email address:</h2>
<xsl:value-of select="me/email" />
<h2>Web site URL:</h2>
<xsl:value-of select="me/url" />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
So I've got the XML data and the XSLT stylesheet. All that remains is to put
them together - which is where PHP comes in. Take a look at the following script, which brings it all together:
<?php
// store XML and XSL content as variables
$xmlstring = join('', file('person.xml'));
$xslstring
= join('', file('person.xsl'));
// call the XSLT processor directly
xslt_process($xslstring, $xmlstring, $result);
// output the result
echo $result;
?>
Let's dissect this a little.
1. First, I've used the file() function to read the contents of the XML document and XSLT stylesheet into an array, and then used PHP's very cool join() function to combine all the elements of the array (which correspond to lines from the file) into a single string. Each string is then stored as a variable.
$xmlstring = join('', file('person.xml'));
$xslstring = join('', file('person.xsl'));
2. You're probably wondering why I bothered. Well, the xslt_process() function,
which happens to be PHP's primary workhorse for this sort of thing, accepts three parameters: an XML data string, an XSLT data string, and a variable to hold the results of the transformation.
xslt_process($xslstring, $xmlstring, $result);
3. Once the processing is complete, and $result contains the output, all that's
left is to print it.
echo $result;
Next: Handling Things Better >>
More XML Articles
More By Harish Kamath, (c) Melonfire