Key Takeaways
- XSLT (XSL Transformations) can be integrated into a traditional Content Management System (CMS) to simplify coding and provide better error-checking for custom tags.
- XSLT functionality in PHP was introduced with PHP 4.1.0 and can be set up with an XSL processor to transform XML data in a server-side language like PHP.
- The process of setting up XSLT in PHP involves installing PHP without XSLT support, enabling the XSLT module, installing the open-source Sablotron XSLT processor, and then enabling the PHP extension for XSLT support.
- Once XSLT support is activated in PHP and the web server restarted, PHP will be equipped to process XML data with XSLT, transforming it into HTML with an XSL stylesheet. This can be used to serve content from a database, making it more adaptable for different uses.
In Get XSL To Do Your Dirty Work, we looked at XSL Transformations (XSLT) and how an XSL processor can be integrated into a traditional Content Management System (CMS). We saw how an XSL processor can take a lot of the grunt work out of coding your average CMS and provide better error-checking for custom tags.
If I convinced you that XSL is something you want to add to your next database-driven Website, you’re probably anxious to learn how to integrate an XSL processor with the server-side language of your choice. While many options exist in this arena, this article will show you how to set up and use an XSL processor in PHP, a popular server-side language in the SitePoint community.
NOTE: The XSLT functionality in PHP that is covered in this article was introduced with PHP 4.1.0. PHP saw several experimental revisions of its XSLT module before this release; however, they differed in many ways from the module described here. Please be sure you have PHP 4.1.0 or later before proceeding.
XSLT Module Install for Windows
The first thing you need to do is get PHP up and running on your Windows-based Web server (be it Apache, IIS, or whatever) without XSLT support. If you need help with that, check out my article, Build your own Database Driven Website using PHP & MySQL – Part 1: Installation, which will walk you through the process.
Once you have PHP up and running, the next step is to enable the XSLT module that it comes with. To function, this module makes use of the open-source Sablotron XSLT processor. Sablotron, in turn, relies on the open-source XML parser, Expat. Here’s how to install these on your Windows system:
- Download Expat from the project Web site on SourceForge. You’ll want the latest version of the expat_win32bin package.
- Install Expat as you would any other program into a convenient directory on your system.
- Locate the
expat.dll
file in theLibs
subdirectory of your Expat installation, and copy it to your WindowsSYSTEM32
directory (e.g.C:WINDOWSSYSTEM32
). - Download Sablotron from the Ginger Alliance Web site. The ‘Windows binary’ release is the one you’re after.
- Extract the ZIP file to a convenient place on your system. A
Sablot-version
directory will be created for you. - Locate the
sablot.dll
file in thebin
subdirectory of your Sablotron installation, and copy it to your WindowsSYSTEM32
directory.
With the required software in place, you can now enable the PHP extension for XSLT support. Open your php.ini
file and locate the extension_dir
line. Either set it to the extensions
directory of your PHP installation, or copy the php_xslt.dll
file in that directory to the directory specified by this setting. Then, uncomment (remove the ;
from the beginning of) or add the following line to the section under ‘Windows Extensions’:
extension=php_xslt.dll
With those changes made, save the updated file and close the editor. You’ve just activated XSLT support in your PHP installation. For this change to affect your Web server, you’ll need to restart it (or just restart your computer, which has the same effect, if you’re the lazy type).
Once your Web server starts back up, PHP should be fully equipped to process XML data with XSLT. To make sure, you can create a simple PHP script that just calls phpinfo()
, then view the results on your server. The page produced should contain the following section:
Now skip past the Linux installation procedure and we’ll take the XSLT functions for a test drive.
XSLT Module Install for Linux
XSLT support in PHP relies on the Sablotron XSLT processor, which in turn relies on the expat XML parser, so not only do you have to install both of those packages, but you need to install them in the right order to satisfy the dependencies.
First, download the latest version of expat (1.95.2 as of this writing). Steer clear of the .RPM packages. Though they may be convenient, they do not include the libraries required for Sablotron to use expat. Download the source archive (expat-1.95.2.tar.gz
) and then extract it in a convenient directory:
tar xfz expat-1.95.2.tar.gz
This will create a directory named expat-1.95.2
that contains the files required to compile and install expat. Go into that directory and type the following commands to configure, compile, and install expat with the default options. You’ll likely have to log in as the root user to perform the make install
, which installs new system libraries to non-public directories. Consult the expat documentation if you want to modify the default options.
./configure
make
make install
With expat compiled and installed, you’re now ready to do the same for Sablotron. Download the latest version (0.71 as of this writing). Once again, you want the source download (Sablot-0.71.tar.gz
), not the RPMs, though you might have a shot if you installed both the sablotron
and sablotron-devel
RPMs (try at your own risk!). Extract the source archive as you did for expat:
tar xfz Sablot-0.71.tar.gz
Go into the directory thus produced (Sablot-0.71
) and run the following commands to configure, compile, and install Sablotron. The configuration process should detect your expat installation automatically. Once again, you should log in as root to perform the make install
.
./configure
make
make install
Finally, you’re ready to compile and install PHP with XSLT support. Presumably you already have PHP installed on your server, but as with most module installations, you’ll have to download the PHP source files and recompile PHP to add XSLT support. This process is fully documented in Build your own Database Driven Website using PHP & MySQL – Part 1: Installation; all that changes is the set of switches you need to use when configuring PHP prior to compilation:
./configure
--prefix=/usr/local/php
--with-config-file-path=/usr/local/php
--with-apxs=/usr/sbin/apxs
--enable-track-vars
--enable-magic-quotes
--enable-debugger
--enable-xslt
--with-xslt-sablot
The lines in bold add XML and XSLT support to your PHP configuration. From there, PHP installation should be completed as usual by performing a make
and then a make install
. Once you restart your Web server with the newly-compiled PHP module installed, PHP should be fully equipped to process XML data with XSLT. To make sure, you can create a simple PHP script that just calls phpinfo()
, then view the results on your server. The page produced should contain the following section:
Now let’s take the XSLT functions for a test drive.
Test Drive
To try out the new XSLT functionality we’ve just set up in PHP, I’m going to return to the simple DocBook sample document I used in Get XSL To Do Your Dirty Work. Here’s the document in question:
<?xml version="1.0" encoding="UTF-8"?>
<article>
<title>A Sample Article</title>
<section>
<title>Article Section 1</title>
<para>
This is the first section of the article. Nothing terribly
interesting here, though.
</para>
</section>
<section>
<title>Another Section</title>
<para>
Just so you can see how these things work, here's an
itemized list:
</para>
<itemizedlist>
<listitem>
<para>The first item in the list</para>
</listitem>
<listitem>
<para>The second item in the list</para>
</listitem>
<listitem>
<para>The third item in the list</para>
</listitem>
</itemizedlist>
</section>
</article>
Note that I’ve left out the DOCTYPE declaration at the top of the file. Since the expat XML parser that the Sablotron XSLT processor uses is not a validating parser, the DOCTYPE only serves to slow down the parsing in most cases (as a concession to XML know-it-alls in the audience, there are exceptions).
Here’s the XSL stylesheet we developed to display documents in the above format:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="article">
<html>
<head>
<title><xsl:value-of select="title"/></title>
</head>
<body>
<h1><xsl:value-of select="title"/></h1>
<xsl:apply-templates select="section"/>
</body>
</html>
</xsl:template>
<xsl:template match="section">
<xsl:apply-templates/>
<hr/>
</xsl:template>
<xsl:template match="section/title">
<h2><xsl:apply-templates/></h2>
</xsl:template>
<xsl:template match="para">
<p><xsl:apply-templates/></p>
</xsl:template>
<xsl:template match="itemizedlist">
<ul><xsl:apply-templates/></ul>
</xsl:template>
<xsl:template match="listitem">
<li><xsl:apply-templates/></li>
</xsl:template>
</xsl:stylesheet>
Save these on your Web server as docbook.xml
and docbook.xsl
respectively, then create docbook.php
. It will be the job of this script to transform docbook.xml
according to the rules in docbook.xsl
and to send the HTML output to the user’s Web browser.
Here’s the code for docbook.php
:
<?php
// Create an XSLT processor
$xsltproc = xslt_create();
// Perform the transformation
$html = xslt_process($xsltproc, 'docbook.xml', 'docbook.xsl');
// Detect errors
if (!$html) die('XSLT processing error: '.xslt_error($xsltproc));
// Destroy the XSLT processor
xslt_free($xsltproc);
// Output the resulting HTML
echo $html;
?>
This comments in the above code should explain it well. For more information on the functions in use, refer to the PHP manual’s section on XSLT processing functions (http://www.php.net/manual/en/ref.xslt.php).
Try this on your server, which has been newly-equipped with XSLT procesing capabilities. You should see the HTML version of the document produced by the Sablotron XSLT engine!
It’s quite straightforward to modify this script to serve content from your database. Just pull the XML code stored in your database out in the usual fashion, then use xslt_process
to transform it into HTML with an XSL stylesheet. The stylesheet can be stored in your database, generated dynamically, or just kept in a file on your server as in the example above.
Explore the rest of the XSLT functions in PHP and you’ll be ready to get started on your XSLT-based CMS!
Frequently Asked Questions (FAQs) about Transforming PHP with XSLT
What is XSLT and why is it important in PHP?
XSLT stands for Extensible Stylesheet Language Transformations. It is a language used for transforming XML documents into other types of documents such as HTML, PDF, or other XML documents. In PHP, XSLT is important because it allows developers to change the structure and content of an XML document, making it more flexible and adaptable for different uses. This is particularly useful when dealing with large amounts of data that need to be displayed in various ways.
How do I install and configure XSLT in PHP?
To use XSLT in PHP, you need to install the PHP XSL extension. This can be done through the PHP.ini file by uncommenting the line “;extension=xsl”. After installation, you can use the XSLTProcessor class to transform XML documents.
How do I use the XSLTProcessor class in PHP?
The XSLTProcessor class in PHP is used to transform XML documents. First, you need to create an instance of the class. Then, you can load the XSL stylesheet using the ‘importStylesheet’ method and the XML document using the ‘transformToXML’ method.
Can I use XSLT to transform XML into HTML in PHP?
Yes, XSLT can be used to transform XML documents into HTML. This is done by creating an XSL stylesheet that defines how the XML elements should be transformed into HTML elements. The XSLTProcessor class can then be used to apply this stylesheet to the XML document.
What are some common errors when using XSLT in PHP and how can I troubleshoot them?
Common errors when using XSLT in PHP include issues with the XSL stylesheet, such as syntax errors or missing elements, and problems with the XML document, such as invalid characters or incorrect structure. These can be troubleshooted by checking the XSL and XML files for errors, and using error handling functions in PHP to catch and handle any exceptions.
How can I improve the performance of XSLT transformations in PHP?
Performance of XSLT transformations in PHP can be improved by optimizing the XSL stylesheet, such as by reducing complexity and avoiding unnecessary transformations. Caching can also be used to store the results of transformations, reducing the need to perform them again.
Can I use XSLT with other programming languages besides PHP?
Yes, XSLT is a language-independent technology and can be used with many other programming languages, including Java, C#, and Python.
How can I use XSLT to transform XML into other XML formats in PHP?
To transform XML into other XML formats using XSLT in PHP, you need to create an XSL stylesheet that defines the transformation rules. The XSLTProcessor class can then be used to apply this stylesheet to the XML document.
What are the benefits of using XSLT in PHP?
Using XSLT in PHP provides several benefits, including the ability to transform XML documents into various formats, flexibility in handling and displaying data, and improved performance through optimization and caching.
Are there any alternatives to XSLT for transforming XML in PHP?
Yes, there are several alternatives to XSLT for transforming XML in PHP, including using DOM or SimpleXML to manipulate the XML document directly. However, these methods may not provide the same level of flexibility and performance as XSLT.
Kevin Yank is an accomplished web developer, speaker, trainer and author of Build Your Own Database Driven Website Using PHP & MySQL and Co-Author of Simply JavaScript and Everything You Know About CSS is Wrong! Kevin loves to share his wealth of knowledge and it didn't stop at books, he's also the course instructor to 3 online courses in web development. Currently Kevin is the Director of Front End Engineering at Culture Amp.