Saturday, December 20, 2008

PHP - Using PHP for XSLT transformations

Templating using XSL Transformation is a technique that is becoming more and more popular. PHP 5 has support for XSLT. But the best thing about using XSLT in PHP is that, php supports calling native functions in PHP from the XSL template. This increases the power of XSL transformation by several folds. Here is an example on how to transform xml to xhtml using php and use native php functions.


<?php
// Set default time zone
date_default_timezone_set('Asia/Calcutta');
$xmlStr = <<<STR
<Profiles>
<Profile>
  <id>1</id>
  <name>john doe</name>
  <dob>188677800</dob>
</Profile>
<Profile>
  <id>2</id>
  <name>mark antony</name>
  <dob>79900200</dob>
</Profile>
<Profile>
  <id>3</id>
  <name>neo anderson</name>
  <dob>240431400</dob>
</Profile>
<Profile>
  <id>4</id>
  <name>mark twain</name>
  <dob>340431400</dob>
</Profile>
<Profile>
  <id>5</id>
  <name>frank hardy</name>
  <dob>390431400</dob>
</Profile>
</Profiles>
STR;
$xslStr = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" exclude-result-prefixes="php">
<xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes" standalone="no" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"/>
<xsl:template match="/">
  <html>
    <head>
      <title>User Profiles</title>
    </head>
    <body>
      <h1>Using PHP Functions in XSLT</h1>
      <table cellspacing="1" cellpadding="5" border="1">
         <caption>User Profiles</caption>
         <tr><th>ID</th><th>Name</th><th>Date of Birth</th></tr>
         <xsl:for-each select="/Profiles/Profile">
         <tr>
            <td><xsl:value-of select="id"/></td>
            <td><xsl:value-of select="php:function('ucwords', string(name))"/></td>
            <td><xsl:value-of select="php:function('date', 'jS M, Y', number(dob))"/></td>
         </tr>
         </xsl:for-each>
      </table>
    </body>
  </html>
</xsl:template>
</xsl:stylesheet>
EOB;

$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xmlStr);

$xslDoc = new DOMDocument();
$xslDoc->loadXML($xslStr);

$xsltProcessor = new XSLTProcessor();
$xsltProcessor->registerPHPFunctions();
$xsltProcessor->importStyleSheet($xslDoc);
echo
$xsltProcessor->transformToXML($xmlDoc);
?>

No comments: