John's Blog

home info

XSL Transform - Use xsl transforms in your web page

XSL transforms are a great, usually efficient, way to extract data from an XML document, and create part of a web page - or even the entire page. There are many ways to perform the transform, XSLTPROC1, and SAXON2, are two popular choices.

This works fine, if the page is static - that is, created once and viewed many times after that. The difficulty arises when the page needs to be dynamic - responding to a button click, or a link. 

One of the easiest ways to accomplish dynamic XSL translation in a web page is with PHP, and the XSLTProcessor class. This will allow you to run an XSL Stylesheet dynamically.

The process is to

  1. create a DOM Document and load the XML into it
  2. create another DOM Document and load the XSL into it
  3. create an XSLTProcessor
  4. attach the xsl rules (the second DOM document) to it.
  5. run the XSLTProcessor against the first DOM Document (the xml)

To make the whole process easier, I wrote a function:

<?php
function xsltTransform($theXML, $theXSL, $theParams = null) {
	$xml = new DOMDocument;
	$xml->load($theXML);
	$xsl = new DOMDocument;
	$xsl->load($theXSL);
	// Configure the transformer
	$proc = new XSLTProcessor;
	$proc->importStyleSheet($xsl); // attach the xsl rules
	//
	if ($theParams) {
		foreach ($theParams as $key => $value) {
			$proc->setParameter('', $key, $value);
		}
	}
	//
	return $proc->transformToXML($xml);
}
?>

Note that this will allow parameters to be fed to the stylesheet, in a similar way to XSLTPROC's --stringparam option.


1. XSLTPROC man page.

2. SAXON website.

Author: JMP (Saturday 24th of July 2021 05:14:42 AM)




News

More simplification of the blog - enjoy!