XSLT 是一個非常方便的轉換 XML 的工具,PHP 里面是通過 XSLTProcessor 來實現;XSLT 中內置了許多有用的函數,同時,只需要調用 XSLTProcessor 實例的 registerPHPFunctions 方法,我們就可以在 XSLT 中直接使用 PHP 的函數,這大大增強了 XSLT 的處理能力。
但是,在 XSLT 中使用 PHP 函數時,很多人會遇到如下兩種錯誤:
(1)、Warning: XSLTProcessor::transformToXml(): xmlXPathCompiledEval: 1 objects left on the stack.
(2)、PHP Warning: XSLTProcessor::transformToXml(): xmlXPathCompOpEval: function function 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">
新聞熱點
疑難解答