views:

67

answers:

3

I want to use a combination of xml & xslt as a templating system. The question that I want answered is: can xslt and PHP communicate with each other (i.e share variables)?

+1  A: 

XSLT is a language, not a piece of software. It entirely depends what software you are using to process your XSLT: if it is a PHP extension, running as part of your existing PHP app, then yes. Otherwise, no.

Colin Fine
PHP does have an extension for XSLT, and, in this case I just need to be able to include a php file into a xslt file and share some php variables with the xslt file.
Tunji Gbadamosi
A: 

What exactly do you mean by "share variables"? Do you want a PHP script to generate XSLT first and use that output in another PHP script to render your XML data? If so, then yes, that's possible. It doesn't matter where the XSLT comes from.

wimvds
+1  A: 

The basic task you can do with PHP is to define which XML file to transform with which XSLT script. Using this you can
a) pass parameters from PHP to XSLT and
b) use PHP functions in the XSLT script.
This example shows how - first PHP file:

<?php
function f($value){
  //do something
  return $value;
}
$proc=new XsltProcessor;
$proc->registerPHPFunctions();
$proc->setParameter('', 'p', '123');
$proc->importStylesheet(DOMDocument::load("script.xsl"));
echo $proc->transformToXML(DOMDocument::load("data.xml"));
?>

second XSLT file:

<?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:param name="p" select="''"/>
  <xsl:template match="/">
    <xsl:value-of select="$p"/> 
    <xsl:value-of select="php:function('f', '456')"/>
  </xsl:template>
</xsl:stylesheet>

The output should be 123456
EDITED: select="''" instead select=""

Andreas