O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

PHP 4

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));
}

xslt_free($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.

PHP 5

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;
$xsl->load('stylesheet.xsl');

// Create new XSLTProcessor
$xslt = new XSLTProcessor( );                                                                                                                       
// Load stylesheet
$xslt->importStylesheet($xsl);

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'); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required