12

我想知道是否以及如何使用 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:functionArrayphp:functionSetphp:functionList都不起作用。

在 PHP 手册中,我可以返回另一个DOMDocument包含元素,但是这些元素不再来自原始文档。这对我来说没有多大意义。

4

1 回答 1

4

对我有用的是返回一个实例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()从函数返回的对象。

于 2013-06-04T15:16:27.910 回答