Transforming XML Using XSLT

XSLT is an XML-based language that allows you to manipulate XML documents before outputting them. With one XML document, you can make the same content look vastly different—for example, you could transform it with a WML XSL stylesheet and send it to WAP devices, or parse it with an SQL XSL stylesheet and send it to a database.

Several browsers (most notably Firefox and Internet Explorer) can perform XSL transformation on the client side by downloading an XML document, the XSL stylesheet, and any accompanying CSS files, then combining them all together on your visitor's computer. But someone with an old version of IE, or any other non-XSL-enabled browser, would not get the same experience.

This is where PHP comes in: your visitor types a URL as usual, but it is PHP that loads the XML and the XSL and combines the two together into the output. On the client side, users see no XML or XSL at all, just normal XHTML. Of course, there is nothing stopping that PHP page from analyzing the visitor's user agent and sending content fit for that browser, whether it be HTML 2, XHTML, WAP, or anything else.

An Example XSL Document

Here is an example XSL document designed to work on the employees.xml file from before. Save it in the same directory, as input.xsl:

 <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://my.netscape.com/rdf/simple/0.9/"> ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.