PHP 可以与 XSLT 通信吗?

我想结合使用 xml &xslt 作为模板系统.我想回答的问题是:xslt 和 PHP 可以互相通信吗(即共享变量)?

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)?

推荐答案

您可以使用 PHP 完成的基本任务是定义要使用哪个 XSLT 脚本转换哪个 XML 文件.使用这个你可以
a) 将参数从 PHP 传递到 XSLT 和
b) 在 XSLT 脚本中使用 PHP 函数.
这个例子展示了如何 - 第一个 PHP 文件:

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"));
?>

第二个 XSLT 文件:

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>

输出应该是 123456
select="''" 而不是 select=""

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

相关文章