Before and After: Transforming XML with XSLT

PHP 4 has a separate XSLT extension that relies on the Sablotron XSLT parsing library. In PHP 5, that’s replaced by integrated XSLT support with the DOM functions. Also, libxslt has replaced Sablotron as the processor of choice.


In PHP 4, the XSLT extension uses resources instead of objects:

$xml = 'data.xml';
$xsl = 'stylesheet.xsl';

$xslt = xslt_create( );
$results = xslt_process($xslt, $xml, $xsl);

if (!$results) {
    error_log("XSLT Error: #".xslt_errno($xslt).": ".xslt_error($xslt));


You pass xslt_process( ) the filenames of your XML and XSLT documents, and it loads the XML from disk. You can also read in from a variable (using the weird argument syntax), but not from a DOM object.


Using XSLT in PHP 5 involves two main steps: preparing the XSLT object and then triggering the actual transformation for each XML file.

To begin, load in the stylesheet using DOM. Then, instantiate a new XSLTProcessor object, and import the XSLT document by passing in your newly created DOM object to the importStylesheet( ) method.

// Load XSL template
$xsl = newDOMDocument;

// Create new XSLTProcessor
$xslt = new XSLTProcessor( );                                                                                                                       
// Load stylesheet

Now the transformer is up and running. You can transform any DOM object in one of three ways: into a string, into a file, or back into another DOM object.

// Load XML input file $xml = newDOMDocument; $xml->load('data.xml'); ...

Get Upgrading to PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.