HomeXML Page 4 - XSL Transformation With PHP And Sablotron
Handling Things Better - 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.
Now, though the script you just saw is pretty primitive, it gets the job done. However, when you're working on a real project, you need to be more professional in your approach. So let's take this to the next level, with a slightly different version of the script above:
<?php
// the files
$xmlfile = "person.xml";
$xslfile = "person.xsl";
// create the XSLT processor
$xslthandler = xslt_create() or die("Houston, we
have a problem. No XSLT
handler available. Mission aborted.");
// process the two files to get the desired output
xslt_run($xslthandler, $xslfile,
$xmlfile);
// get and print the result
echo xslt_fetch_result($xslthandler);
// free the resources occupied by the handlers
xslt_free($xslthandler);
?>
This is a slightly more structured approach. After defining the filenames for
the XML and XSLT content, I've used the xslt_create() function to create a new instance of the XSLT processor and return a handle to it.
// create the XSLT processor
$xslthandler = xslt_create() or die("Houston, we
have a problem. No XSLT
handler available. Mission aborted.");
This handle is used in all subsequent XSLT operations.
Next, I've used the xslt_run() function to read and process the XML and XSLT files, and store the results of the processing in the default result buffer.
// process the two files to get the desired output
xslt_run($xslthandler, $xslfile,
$xmlfile);
Once the processing is complete and the output dumped into the default result
buffer, I've used the xslt_fetch_result() function to fetch the contents of the buffer and print it to the browser.
// get and print the result
echo xslt_fetch_result($xslthandler);
Finally, it's a good idea to clean things up by destroying the handle created
during this process, so as to not occupy valuable memory.
// free the resources occupied by the handlers
xslt_free($xslthandler);
The xslt_free() function frees up the memory occupied by the XSLT processor.
Using xslt_run() is often preferable to using xslt_process(), since the xslt_run() function is happy to accept file references to the XML and XSLT data as arguments (as opposed to xslt_process(), which only accepts string variables). Using xslt_run() can, therefore, often save you a few lines of code when performing server-side transformation with PHP.