Transform your PHP with XSLT

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 the Libs subdirectory of your Expat installation, and copy it to your Windows SYSTEM32 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 the bin subdirectory of your Sablotron installation, and copy it to your Windows SYSTEM32 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:

Identifying XSLT support in PHPNow 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:

Identifying XSLT support in PHPNow 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="http://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!

A DocBook document transfored to HTML with XSLT in PHPIt’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!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments

Comments on this post are closed.