我想知道是否以及如何能够向XSLT处理器注册一个PHP用户空间函数,这个处理程序不仅能够接收一个节点数组,而且还可以返回它?
现在,PHP抱怨使用公共设置将数组转换为字符串:
function all_but_first(array $nodes) {
array_shift($nodes);
shuffle($nodes);
return $nodes;
};
$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStylesheet($xslDoc);
$buffer = $proc->transformToXML($xmlDoc);例如,要转换的XMLDocument ($xmlDoc)可以是:
<p>
<name>Name-1</name>
<name>Name-2</name>
<name>Name-3</name>
<name>Name-4</name>
</p>在样式表中它被称为如下所示:
<xsl:template name="listing">
<xsl:apply-templates select="php:function('all_but_first', /p/name)">
</xsl:apply-templates>
</xsl:template>通知如下:
注意:数组到字符串的转换
我不明白为什么如果函数得到一个数组,因为输入也不能返回一个数组?
我还尝试了其他“函数”名称,就像我看到的那样,这里有php:functionString,但是到目前为止,所有尝试都没有成功(php:functionArray、php:functionSet和php:functionList)。
在PHP手册中,我可以返回另一个包含元素的DOMDocument,但是这些元素不再来自原始文档。这对我来说没什么意义。
发布于 2013-06-04 15:16:27
对我有用的是返回一个DOMDocumentFragment实例,而不是一个数组。因此,为了在您的示例中进行尝试,我将您的输入保存为foo.xml。然后我让foo.xslt看起来像这样:
<xsl:stylesheet version="1.0" xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:php="http://php.net/xsl">
<xsl:template match="/">
<xsl:call-template name="listing" />
</xsl:template>
<xsl:template match="name">
<bar> <xsl:value-of select="text()" /> </bar>
</xsl:template>
<xsl:template name="listing">
<foo>
<xsl:for-each select="php:function('all_but_first', /p/name)">
<xsl:apply-templates />
</xsl:for-each>
</foo>
</xsl:template>
</xsl:stylesheet>(这只是一个使用xsl:stylesheet包装器来调用它的示例。)而这件事的真正核心,foo.php
<?php
function all_but_first($nodes) {
if (($nodes == null) || (count($nodes) == 0)) {
return ''; // Not sure what the right "nothing" return value is
}
$returnValue = $nodes[0]->ownerDocument->createDocumentFragment();
array_shift($nodes);
shuffle($nodes);
foreach ($nodes as $node) {
$returnValue->appendChild($node);
}
return $returnValue;
};
$xslDoc = new SimpleXMLElement('./foo.xslt', 0, true);
$xmlDoc = new SimpleXMLElement('./foo.xml', 0, true);
$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStylesheet($xslDoc);
$buffer = $proc->transformToXML($xmlDoc);
echo $buffer;
?>重要的部分是调用ownerDocument->createDocumentFragment()使从函数返回的对象。
https://stackoverflow.com/questions/12960211
复制相似问题