在 XSLTProcessor 中 registerPHPFunctions 后无法调用 php 函数解决办法
但是,在 XSLT 中使用 PHP 函数时,很多人会遇到如下两种错误:
(1) Warning: XSLTProcessor::transformToXml(): xmlXPathCompiledEval: 1 objects left o
n the stack.
(2)PHP Warning: XSLTProcessor::transformToXml(): xmlXPathCompOpEval: function func
tion bound to undefined prefix php in ….
代码如下 |
复制代码 |
<?php
$xml = <<<EOB
<allusers>
<user>
<uid>bob</uid>
</user>
<user>
<uid>joe</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">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
<xsl:template match="allusers">
<html><body>
<h2>Users</h2>
<table>
<xsl:for-each select="user">
<tr><td>
<xsl:value-of
select="php:function('ucfirst',string(uid))"/>
</td></tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
EOB;
$xmldoc = DOMDocument::loadXML($xml);
$xsldoc = DOMDocument::loadXML($xsl);
$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
?>
|
其实,出现这种错误,是因为我们没有定义 PHP namespace ,只需要在
代码如下 |
复制代码 |
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
|
中增加 xmlns:php="http://php.net/xsl" 就能解决此问题, 即
代码如下 |
复制代码 |
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl">
|
补充:Php教程,常见问题