HomeXML Page 3 - XSL Transformation With PHP And Sablotron
Start It Up - XML
So you've got your XML, and you've also got an XSLT stylesheet to format it. But how do you put the two of them together? Fear not - you can use PHP's Sablotron extension to perform XSLT transformation of XML data on the server. This article tells you how.
<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.
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.