PHP

Transforming XML with XSL and PHP 4

$result = $xslt->process($dom);
echo $xslt->result_dump_mem($result);

To use XSL Transformations (XSLT) with PHP, you again have to decide first which PHP version to use. If it's PHP 4, you have to use extension=php_xslt.dll in php.ini (Windows), or install Sablotron from http://www.gingerall.com/ and use the configuration switches enable-xslt with-xslt-sablot (for other systems).

Using XSLT with PHP 4

<?php
  $dom = domxml_open_mem(file_get_contents('quotes.xml'));
  $xslt = domxml_xslt_stylesheet(
file_get_contents('quotes.xsl'));
  $result = $xslt->process($dom);
  echo $xslt->result_dump_mem($result);
?>

Doing the transformation is a number of four easy steps: Load the XML; load the XSLT; execute the transformation; and, finally, save the result. The preceding coding contains the code for these steps; the file quotes.xsl in the download repository contains markup that transforms the quotes' XML into the well-known HTML bulleted list.

Transforming XML with XSL and PHP5

$result = $xslt->transformToDoc($xml);
echo $result->saveXML();

On PHP 5, XSLT is done by libxslt and can be enabled using php_xsl.dll (in php.ini) on Windows and the switch with-xsl on other platforms. The approach is a bit different: Load both the XML and the XSLT (which is an XML document, as well) into a DOM object, then instantiate an XsltProcessor object. Call importStylesheet() and then transformToDoc().

Using XSLT with PHP5

<?php
  $xml = new DOMDocument();
  $xml->load('quotes.xml');
  $xsl = new DOMDocument();
  $xsl->load('quotes.xsl');
  $xslt = new XsltProcessor();
  $xslt->importStylesheet($xsl);
  $result = $xslt->transformToDoc($xml);
  echo $result->saveXML();
?>

Once again, there is a script that makes the two incompatible XSLT implementations compatible with each other. You find it at http://alexandre.alapetite.net/doc-alex/xslt-php4-php5/.

by BrainBellupdated
Advertisement: