O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

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

Transforming XML with XSLT

Extensible Stylesheet Language Transformations (XSLT) is a language for transforming XML documents into different XML, HTML, or any other format. For example, many websites offer several formats of their content—HTML, printable HTML, and WML (Wireless Markup Language) are common. The easiest way to present these multiple views of the same information is to maintain one form of the content in XML and use XSLT to produce the HTML, printable HTML, and WML.

PHP’s XSLT extension uses the libxslt C library to provide XSLT support.

Three documents are involved in an XSLT transformation: the original XML document, the XSLT document containing transformation rules, and the resulting document. The final document doesn’t have to be in XML—a common use of XSLT is to generate HTML from XML. To do an XSLT transformation in PHP, you create an XSLT processor, give it some input to transform, and then destroy the processor.

Create a processor by creating a new XsltProcessor object:

$processor = new XsltProcessor;

Parse the XML and XSL files into DOM objects:

$xml = new DomDocument;
$xml->load($filename);

$xsl = new DomDocument;
$xsl->load($filename);

Attach the XML rules to the object:

$processor->importStyleSheet($xsl);

Process a file with the transformToDoc(), transformToUri(), or transformToXml() methods:

$result = $processor->transformToXml($xml);

Each takes the DOM object representing the XML document as a parameter.

Example 11-10 is the XML document we’re going to transform. ...

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