Calling PHP Functions from XSL

nadeem.shabir | | Saturday, July 14th, 2007

Craig, a colleague of mine who newly joined our development team at Talis showed me this neat little trick. Many things are far easier to do in PHP than they are in XSL, and some things simply can’t be done in pure XSL. A solution is to call PHP functions directly from within your XSL.

1) In your xsl stylesheet add:

   namespace xmlns:php="http://php.net/xsl"
   exclude-result-prefixes="php"

2) To call the php function and access the result use:

  1.  
  2.   <!– for string use this –>
  3.   <xsl:value-of select="php:functionString(‘phpFunctionName’, /xpath)"/>
  4.  
  5.   <!– for DOM Nodes use this –>
  6.   <xsl:copy-of select="php:function(‘phpFunctionName’, /xpath)"/>
  7.  

You can pass as many parameters as you want to either php:function or php:functionString – the latter merely converts output to a string and otherwise they are identical.

3) you must register them with the XSL Transformer:

  1.  
  2. $doc = new DOMDocument();
  3. $xsl = new XSLTProcessor();
  4.  
  5. $doc->load($xsl_filename);
  6. $xsl->importStyleSheet($doc);
  7.  
  8. $doc->load($xml_filename);
  9.  
  10. $xsl->registerPHPFunctions(); // This is the important call for this functionality
  11.  
  12. echo $xsl->transformToXML($doc);
  13.  

4) In your php function, access parameters passed in as strings as if they are a php string. If you pass a dom structure as a parameter then you need to access it along the lines of:

  1.  
  2. function ProcessDomFromXslCall($DomList) {
  3.    $NodeList = $DomList[0]->getElementsByTagNameNS(‘namespace’, ‘element-name’);
  4.    for($i=0; $i<$NodeList->length; $i++) {
  5.      echo $i, $NodeList->item($i)->nodeValue;
  6.    }
  7.  }
  8.  

$DomList will include the root element of the XPath used to call the PHP function

If you want to dump what you pass to PHP as a string you need to do:

  1.  
  2.  function DumpStuff($DomElements) {
  3.    echo $DomElements[0]->C14N(); // note this function isn’t yet documented in the PHP manual !
  4.  }
  5.  

It’s a very useful feature … good luck with it.

Powered by WordPress | Theme by Roy Tanck