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:functionArrayおよびphp: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 に答える