在 XSLT 中調用 PHP 函數時出現錯誤:
Warning: XSLTProcessor::transformToXml(): xmlXPathCompOpEval: function function bound to undefined prefix php
Warning: XSLTProcessor::transformToXml(): xmlXPathCompiledEval: 1 objects left on the stack
XSLT 樣式表中未聲明 PHP 命名空間,導致 XPath 解析器無法識別 `php:function()` 前綴。
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="https://www.w3.org/1999/XSL/Transform"
xmlns:php="https://php.net/xsl"> <!-- 關鍵:聲明 PHP 命名空間 -->
<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>
<!-- 調用 PHP ucfirst 函數 -->
<xsl:value-of select="php:function('ucfirst', string(uid))"/>
</td></tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
<?php
$xml = <<<XML
<allusers>
<user><uid>bob</uid></user>
<user><uid>joe</uid></user>
</allusers>
XML;
$xsl = <<<XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="https://www.w3.org/1999/XSL/Transform"
xmlns:php="https://php.net/xsl">
<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>
XSL;
$xmldoc = new DOMDocument();
$xmldoc->loadXML($xml);
$xsldoc = new DOMDocument();
$xsldoc->loadXML($xsl);
$proc = new XSLTProcessor();
$proc->registerPHPFunctions(); // 註冊 PHP 函數支持
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
// 輸出:Bob, Joe (首字母大寫)
?>
<xsl:value-of select="php:function('MyClass::staticMethod', 'arg')"/>
<xsl:value-of select="php:function(array('MyClass', 'staticMethod'), 'arg')"/>
<?php
$obj = new MyClass();
$proc->registerPHPFunctions(); // 全局函數
// 實例方法需通過閉包或靜態包裝調用
$proc->registerPHPFunctions(['myFunc' => [$obj, 'method']]); // 不直接支持
?>
<xsl:value-of select="php:function('processNodes', .)"/>
<?php
function processNodes($nodes) {
// $nodes 是 DOMNodeList
foreach ($nodes as $node) { ... }
return $result;
}
?>
| 錯誤信息 | 原因 | 解決 |
|---|---|---|
| undefined prefix php | 缺少 xmlns:php 聲明 | 添加 xmlns:php="https://php.net/xsl" |
| function bound to undefined prefix | 同左 | 同左 |
| objects left on stack | XPath 表達式結果未正確消費 | 檢查 select 表達式、確保單一結果 |
| PHP function 'xxx' not found | 函數名拼寫錯誤或未定義 | 檢查函數名、命名空間、可見性 |
| DOMDocument::loadXML() error | XML/XSL 格式錯誤 | 驗證 XML 格式、編碼聲明 |