O'Reilly logo

PHP Cookbook by Adam Trachtenberg, David Sklar

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

12.5. Transforming XML with XSLT

Problem

You have a XML document and a XSL stylesheet. You want to transform the document using XSLT and capture the results. This lets you apply stylesheets to your data and create different versions of your content for different media.

Solution

Use PHP’s XSLT extension:

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

The transformed text is stored in $results.

Discussion

XML documents describe the content of data, but they don’t contain any information about how those data should be displayed. However, when XML content is coupled with a stylesheet described using XSL (eXtensible Stylesheet Language), the content is displayed according to specific visual rules.

The glue between XML and XSL is XSLT, which stands for eXtensible Stylesheet Language Transformations. These transformations apply the series of rules enumerated in the stylesheet to your XML data. So, just as PHP parses your code and combines it with user input to create a dynamic page, an XSLT program uses XSL and XML to output a new page that contains more XML, HTML, or any other format you can describe.

There are a few XSLT programs available, each with different features and limitations. PHP currently supports only the Sablotron XSLT processor, but in the future you’ll be able to use other programs, such as Xalan and Libxslt. ...

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