XSL : Using PHP methods directly in XSL

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!


$xml = new DOMDocument();
$xsl = new DOMDocument();
$proc = new XSLTProcessor();

// On précise au parseur que l'on veut utiliser des fonctions PHP en XSL

echo $proc->transformToXML($xml);


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

      <!-- 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)" />



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.



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

Launch the experience