Using PHP 5s XSL Extension to Perform XSL Transformations
By Tony Marston2005-04-19
Performing the XSL Transformation
You will find that there are numerous options available when you come to perform the XSL transformation. Below are some of these options with an explantion of their use.
Creating an XSLT processor resourceThis requires a single simple instruction.
$xp = new XsltProcessor();Identifying and loading the XSL stylesheet
This obtains the XSL stylesheet from an external file and loads it into the XSLT resource. It will also load in any external templates specified with the
// create a DOM document and load the XSL stylesheetIdentifying the XML Document
$xsl = new DomDocument;
$xsl->load('something.xsl');
// import the XSL styelsheet into the XSLT process
$xp->importStylesheet($xsl);
This obtains the XML data from an external file and loads it into a separate document instance.
// create a DOM document and load the XML datatAlternatively the XML document may be created dynamically using the procedure outlined in Using PHP 5's DOM functions to create XML files from SQL data.
$xml_doc = new DomDocument;
$xml_doc->load('something.xml');
Defining Optional Parameters
Use this method to load in any optional parameters which you want to pass to the XSL transformation process. Note that with PHP version 5.0.0 you must load the parameters one at a time:
$xp->setParameter($namespace, 'id1', 'value1');With PHP version 5.1.0 you will be able to create an array of parameters and load them in one go:
$xp->setParameter($namespace, 'id2', 'value2');
$params['id1'] = 'value1';Invoking the XSLT process and displaying the result
$params['id2'] = 'value2';
....
$xp->setParameter($namespace, $params);
This involves using the transformation method of the XSLT resource created ealier with a specified XML document:
// transform the XML into HTML using the XSL file
if ($html = $xp->transformToXML($xml_doc)) {
echo $html;
} else {
trigger_error('XSL transformation failed.', E_USER_ERROR);
} // if
Tutorial Pages:
» Intended Audience
» Prerequisites
» A Sample XML File
» XML File Contents
» A Sample XSL File
» XSL File Contents
» XSL Include Files
» Performing the XSL Transformation
» Sample Output
» References
