首页 > 开发 > Php > 正文

XSLTProcessor 中 registerPHPFunctions 后无法调用 php 函数

2020-06-09 12:53:53
字体:
来源:转载
供稿:网友

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 ….

  1. <?php  
  2. $xml = <<<EOB  
  3. <allusers>  
  4.  <user>  
  5.   <uid>bob</uid>  
  6.  </user>  
  7.  <user>  
  8.   <uid>joe</uid>  
  9.  </user>  
  10. </allusers>  
  11. EOB;  
  12. $xsl = <<<EOB  
  13. <?xml version="1.0" encoding="UTF-8"?>  
  14. <xsl:stylesheet version="1.0" 
  15.      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  
  16. <xsl:output method="html" encoding="utf-8" indent="yes"/>  
  17.  <xsl:template match="allusers">  
  18.   <html><body>  
  19.     <h2>Users</h2>  
  20.     <table>  
  21.     <xsl:for-each select="user">  
  22.       <tr><td>  
  23.         <xsl:value-of  
  24.              select="php:function('ucfirst',string(uid))"/>  
  25.       </td></tr>  
  26.     </xsl:for-each>  
  27.     </table>  
  28.   </body></html>  
  29.  </xsl:template>  
  30. </xsl:stylesheet>  
  31. EOB;  
  32. $xmldoc = DOMDocument::loadXML($xml);  
  33. $xsldoc = DOMDocument::loadXML($xsl);  
  34.    
  35. $proc = new XSLTProcessor();  
  36. $proc->registerPHPFunctions();  
  37. $proc->importStyleSheet($xsldoc);  
  38. echo $proc->transformToXML($xmldoc);  
  39. ?> 

其实,出现这种错误,是因为我们没有定义 PHP namespace,只需要在

  1. <xsl:stylesheet version="1.0" 
  2. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

中增加 xmlns:php="http://php.net/xsl" 就能解决此问题, 即

  1. <xsl:stylesheet version="1.0" 
  2.     xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  3.     xmlns:php="http://php.net/xsl"

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表