我想知道是否可以注册一个
PHP用户空间功能与XSLT处理器,它不仅可以采取一个节点数组,还可以返回它?
现在,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>
通知如下:
Notice: Array to string conversion
我不明白为什么如果函数获取数组,因为输入不能返回数组呢?
我也尝试其他“函数”名称,因为我看到有PHP:functionString,但所有尝试到目前为止(PHP:functionArray,PHP:functionSet和PHP:functionList)没有工作.
在PHP手册中,我写了我可以返回另一个包含元素的DOMDocument,然而这些元素不再是从原始文档.这对我来说没什么意义
对我有用的是返回一个
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',true);
$xmlDoc = new SimpleXMLElement('./foo.xml',true);
$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStylesheet($xslDoc);
$buffer = $proc->transformToXML($xmlDoc);
echo $buffer;
?>
调用ownerDocument-> createDocumentFragment()来创建从函数返回的对象的重要部分.