FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
Architecture & Design
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
January 01, 2002
The Sablotron XSL Processor

W.J. Gilmore

WebReview.com: PHP's Newest Weapon: The Sablotron XSL Processor


At First Glance . . .

It's a love affair: XSL and PHP. The Sablotron XSL Processor really gets your heart pounding. Imagine what it will do for your sites.

Sablotron and XML Technology Resources

Check out the forums found on the following sites for more information:
Ginger Alliance
Sablotron developers read and try to answer all messages here, and new versions and patches are announced here when released.

Zend
A forum for PHP questions and answers.

PHPBuilder.com
A number of PHP forums, including general help, coding help, install help, and more.

DevShed
PHP and XML oriented forums.

The way an Internet developer embraces a new technology is similar to the act of falling in love. If the introduction and initial courting period go well, a lasting relationship is formed. Many days and nights are spent together, and the developer will brag to colleagues about all of the things he's doing with his new love. However, as human nature would have it, developers are often the unfaithful type, and are commonly found carousing with emerging, sexier technologies. In fact, I've been having an ongoing affair with that tramp HTML (everybody loves her), and although she'll always hold a special place in my heart, I feel it's time to move on. So I've been seeing quite a bit of the eXtensible Markup Language (XML) on the side.

Seriously though, there are quite a few reasons why developers should begin learning more about what XML has to offer. One reason is the ease in which XML can be used to communicate information across not only platforms, but a multitude of devices as well. Through the use of an eXtensible Style Sheet (XSL) processor, a single XML document can be parsed and converted into a format recognizable by the requesting client's device. The implications of doing so should be obvious, not only for the internal interests of your organization, but for your clients as well.

Quite interestingly, PHP (another technology close to my heart) has recently incorporated an XSL processing extension into its already exceedingly large array of functionality. Developed by the Czech Republic-based Ginger Alliance, the Sablotron XSL processor is certainly a welcome feature for the many PHP developers who've been eagerly awaiting further additions to PHP's useful XML-parsing capabilities. In this article, I'll introduce you to some of Sablotron's basic functionality, and give you a few examples that should provide the foundation of knowledge you'll need to get jumpstarted using this cool new extension.

To perform the XSL transformation, you'll need three files: the XML file to be transformed, the XSL file that sets the rules for the transformation, and the PHP script that calls the functions made available by the Sablotron processor. If you don't understand what the first two files are or what they do, I suggest reading Bonnie SooHoo's excellent XML/XSL primer. Of course, coding the PHP script is the subject of this article. With that said, let me begin by generalizing code found within this script. The script's functions are:

  • Creating a new XSL processor handle.
  • Reading in the XML and XSL documents.
  • Performing the transformation.
  • Outputting the transformation.
  • Freeing up resources allocated to XSL processor handle.

Let's begin by taking care of the first step in this process. A processor handle is created by executing the function xslt_create(). Here's an example:

$proc_handle = @xslt_create() or die("Can't create XSLT handle!");
Simple enough, right?

The next step involves reading in the XML and XSL documents. For sake of illustration, here's each document, respectively:

Reading in each document actually doesn't involve any special functionality found within the Sablotron processor. This is accomplished using two of PHP's filehandling functions:

<?
$xml_file = "recipes.xml";
$xsl_file = "pcrecipes.xsl";

// Open each file and assign it to a filehandle.
$xml_handle = fopen($xml_file, "r") or die("Can't open XML file!");
$xsl_handle = fopen($xsl_file, "r") or die("Can't open XSL file!");
// Read in the file contents.
$xml_content = fread($xml_handle, filesize($xml_file));
$xsl_content = fread($xsl_handle, filesize($xsl_file));

?>
Next comes the fun part; the XSLT processing. I think you'll be pleasantly surprised about how easy this is. A simple call to xslt_process() is all it takes:

xslt_process($xsl_content, $xml_content, $xsl_tfmtion);
As you can see, three parameters are required. The first two, $xml_content and $xsl_content, are the XSL and XML contents, respectively. The third file is the variable that'll contain the resulting transformation. Chances are you'll then want to output the transformation to the requesting client browser:

echo $xsl_tfmtion;
Okay, we're almost there. After processing is complete, you should free up the processor resources. This is accomplished with the function xslt_free().

<?
$processor = xslt_create();
// do the parsing 
xslt_free($processor);
?>
Putting it all together, a simple transformation script might look like the following:

<?

$xml_file = "recipes.xml";
// XSL for PC browser
$xsl_file = "pcrecipes.xsl";

$proc_handle = @xslt_create() or die("Can't create XSLT handle!");
// Open each file and assign it to a filehandle.
$xml_handle = fopen($xml_file, "r") or die("Can't open XML file!");
$xsl_handle = fopen($xsl_file, "r") or die("Can't open XSL file!");
// Read in the file contents.
$xml_content = fread($xml_handle, filesize($xml_file));
$xsl_content = fread($xsl_handle, filesize($xsl_file));
// Perform the transformation.  xslt_process($xsl_content, $xml_content, $xsl_tfmtion);
// Output the transformed document.
echo $xsl_tfmtion;

// Free up the processor resources.
xslt_free($processor);

?>

Figure 1 The resulting document as rendered within the requesting client's browser.

Implementing Multiple XSLTs

Although I initially alluded to the fact that XML is useful because it can be easily transformed into different formats according to the requirements of the requesting device, for sake of illustration I've only shown how XML can be transformed into HTML. Chances are you'll want to set up a number of style sheets capable of handling transformations geared towards such devices as cell phones, pagers, PDAs, in addition to the regular old PC browser. But how would you know which style sheet to use? Thankfully, PHP handles this problem for t us, providing valuable client information within the variable $HTTP_USER_AGENT. With this in mind, you could modify the above code to dynamically input a different XSLT according to the information found within this variable. For sake of illustration, assume that you want to provide information to both the typical PC browser and a WAP-enabled phone:

<?
// A few phone browsers
$wap_browsers = array("AUR","Eric","Nok","UP.B");
$xml_file = "recipes.xml";
$agent = substr(trim($HTTP_USER_AGENT),0,4);
if (in_array($agent, $wap_browsers)) :
$xsl_file = "phonerecipes.xsl";
else:
$xsl_file = "pcrecipes.xsl";
endif;
. . . 
?>

Of course, the $wap_browsers array doesn't contain a comprehensive list of all available phone browsers. As you continue to tailor your output to the various devices, chances are you might want to build a separate style sheet for each device that could potentially access your application, due to differing screen sizes and features.

Conclusion

As of the time of this writing, the Sablotron extension was so new to the PHP distribution that documentation wasn't even yet available. However, several of the discussion groups are already beginning to buzz about the prospects of this interesting new feature.

If you end up doing anything really cool with this extension, please let me know about it! I'd love to relay it to the WebReview.com readers.


Jason has been an Internet developer since 1995, and is the author of the upcoming Programmer's Introduction to PHP from APress.

RELATED ARTICLES
No Related Articles
TOP 5 ARTICLES
No Top Articles.
DR. DOBB'S CAREER CENTER
Looking for a new job? open | close
Search jobs on Dr. Dobb's TechCareers
Function:

Keyword(s):

State:  
  • Post Your Resume
  • Employers Area
  • News & Features
  • Blogs & Forums
  • Career Resources

    Browse By:
    Location | Employer | City
  • Most Recent Posts:



    MICROSITES
    FEATURED TOPIC

    ADDITIONAL TOPICS

    INFO-LINK



     




    Techweb
    Informationweek Business Technology Network
    InformationweekInformationweek 500Informationweek 500 ConferenceInformationweek AnalyticsInformationweek Events
    Informationweek MagazineGlobal CIOIWK Government ITbMightyByte and SwitchDark Reading
    Digital LibraryIntelligent EnterpriseInternet EvolutionNetwork ComputingPlug Into The CloudDr. DobbsContentinople
    space
    TechWeb Events Network
    InteropVoiceConWeb 2.0 ExpoWeb 2.0 SummitEnterprise 2.0Mobile Business ExpoNoJitter
    Black HatGTECEnergy CampCloud ConnectGov 2.0 ExpoGov 2.0 Summit
    space
    Light Reading Communications Network
    Light ReadingLight Reading AsiaUnstrungCable Digital NewsInternet EvolutionPyramid Research
    Heavy ReadingLight Reading LiveLight Reading InsiderEthrnet ExpoTelco TVTower Technology Summit
    space
    Financial Technology Network
    Advanced TradingBank Systems and TechnologyInsurance and TechnologyWall Street and TechnologyAccelerating WallstreetBST SummitBuyside Trading SummitIT Summit
    space
    Microsoft Technology Network
    MSDNTechNetTotal IT ProTotal Dev ProNET Total Dev Pro CommunitySQL Total Dev Pro Community
    space