XSL : Using PHP methods directly in XSL

2013-05-15
Laurent Bientz

One of new feature of PHP5 is that the class XML/XSL parsing XSLTProcessor can now natively use PHP to perform heavy and cumbersome transformations before. Now, don't need to make a template for ucwords(), just a little bit setup and let's go!

PHP

<?php
$xml = new DOMDocument();
$xml->load('flux.xml');
$xsl = new DOMDocument();
$xsl->load('flux.xsl');
$proc = new XSLTProcessor();

// On précise au parseur que l'on veut utiliser des fonctions PHP en XSL
$proc->registerPHPFunctions();

$proc->importStyleSheet($xsl); 
echo $proc->transformToXML($xml);
?>

XSL

<!--
- Simple test pour appeler une fonction php
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl"
 version="1.0">
<!-- On ajoute surtout le xmlns PHP -->
  <xsl:output method="xml" encoding="UTF-8" indent="yes" />
  <xsl:template match="root">
    <html>

      <!-- On utilise le préfixe php pour appeler la fonction PHP native ucwords() -->
      <xsl:value-of select="php:function('ucwords','php peut désormais être utilisé en xsl')" />
      <!-- Output: 'Php Peut Désormais Etre Utilisé En Xsl' -->

      <!-- On utilise le préfixe php pour appeler une méthode statique de classe -->
      <xsl:value-of select="php:functionString('CLASS_NAME::methodName','param_string_1',//View/param/xml)" />

    </html>
  </xsl:template>
</xsl:stylesheet>

 

Lily - 2013-07-11 03:35:49
Wonderfull great site
Bnitishnitish - 2013-09-01 17:24:56
A couple of notes, sanitize your request variables before pulling data directing into you code. Avoid using double quote for simple string echo as it is extra load on php parsing use single quote instead. Play with MVC type frameworks such as Zends framework to get familiar with design patterns. Nice tutorial for beginners but be warned, I had to fire a bunch of people recently who programmed like this go back to programming basics and learn popular framework methodologies.
Nuran - 2013-10-11 08:24:00
This is way more helpful than annhtiyg else I've looked at.

Comment

USER EXPERIENCE

Wandi invites you to discover a new approach to navigating a website...
Are you ready?

Launch the experience