首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用PHP函数筛选选择节点集?

如何使用PHP函数筛选选择节点集?
EN

Stack Overflow用户
提问于 2012-10-18 17:19:26
回答 1查看 1.3K关注 0票数 12

我想知道是否以及如何能够向XSLT处理器注册一个PHP用户空间函数,这个处理程序不仅能够接收一个节点数组,而且还可以返回它?

现在,PHP抱怨使用公共设置将数组转换为字符串:

代码语言:javascript
复制
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)可以是:

代码语言:javascript
复制
<p>
   <name>Name-1</name>
   <name>Name-2</name>
   <name>Name-3</name>
   <name>Name-4</name>
</p>

在样式表中它被称为如下所示:

代码语言:javascript
复制
<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,但是这些元素不再来自原始文档。这对我来说没什么意义。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-04 15:16:27

对我有用的是返回一个DOMDocumentFragment实例,而不是一个数组。因此,为了在您的示例中进行尝试,我将您的输入保存为foo.xml。然后我让foo.xslt看起来像这样:

代码语言:javascript
复制
<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

代码语言:javascript
复制
<?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()使从函数返回的对象。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12960211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档