在PHP 5.3(以及可能在下面)的XSL样式表中调用PHP函数时,您可以完全访问传递给函数的ownerDocument
个XML节点。
<?php
$xml = <<<EOB
<allusers>
<user>
<uid>bob</uid>
</user>
</allusers>
EOB;
$xsl = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl">
<xsl:output method="text" encoding="utf-8" indent="yes"/>
<xsl:template match="allusers">
<xsl:for-each select="user">
<xsl:value-of
select="php:function('test', uid)"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
EOB;
/**
* Test function
*
* @param DOMElement[] $node
* @return string
*/
function test(array $node)
{
$output = array(
'Document element: '.$node[0]->ownerDocument->documentElement->tagName,
'Node path: '.$node[0]->getNodePath(),
);
return implode(PHP_EOL, $output);
}
$xmldoc = DOMDocument::loadXML($xml);
$xsldoc = DOMDocument::loadXML($xsl);
$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
PHP 5.3中此脚本的输出是:
Document element: allusers
Node path: /allusers/user/uid
从PHP 5.4及更高版本开始,相同的脚本会产生:
Document element: allusers
Node path: /uid
在PHP函数内部,节点路径似乎仅限于“沙盒”DOM文档,节点本身为documentElement
。有趣的是,您仍然可以通过ownerDocument
访问原始文档,但parentNode
和使用parent::*
或ancestor::*
的XPath查询等属性将在给定节点停止。
有没有办法重新获得PHP 5.4及更高版本中ownerDocument
的完全访问权限?我在PHP发行说明中找不到可以解释这个问题的任何内容。
编辑1 :有趣的是,似乎可以从PHP函数中访问节点的nextSibling
,但不能访问previousSibling
。