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'); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access