我想知道是否以及如何使用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);
Run Code Online (Sandbox Code Playgroud)
$xmlDoc要转换的XMLDocument()可以是:
<p>
<name>Name-1</name>
<name>Name-2</name>
<name>Name-3</name>
<name>Name-4</name>
</p>
Run Code Online (Sandbox Code Playgroud)
在样式表中,它被称为:
<xsl:template name="listing">
<xsl:apply-templates select="php:function('all_but_first', /p/name)">
</xsl:apply-templates>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
通知如下:
注意:数组到字符串转换
我不明白为什么如果函数获取数组,因为输入也不能返回数组?
我也想,因为我已经看到有其他的"功能"的名字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>
Run Code Online (Sandbox Code Playgroud)
(这主要只是您使用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;
?>
Run Code Online (Sandbox Code Playgroud)
重要的部分是调用以ownerDocument->createDocumentFragment()创建从函数返回的对象。
| 归档时间: |
|
| 查看次数: |
1123 次 |
| 最近记录: |