傳統 PHP 混雜 HTML 難維護。引入 XML 作為數據載體,XSLT 作為轉換引擎,實現:
extension=php_domxml.dll -- XML DOM 操作 (PHP 4/5 早期)
extension=php_xslt.dll -- XSLT 處理器 (Sablotron/libxslt)
extension=php_iconv.dll -- 字符集轉換 (如 GB2312 ↔ UTF-8)
dlls/ 加入系統 PATH (否則找不到依賴 DLL)。DB.php (資料庫抽象)、XML_Serializer / XML_Util (XML 生成)。php.ini 設 include_path = ".;d:/php/pear"。CREATE TABLE yhxx (
nsrnm VARCHAR(15) PRIMARY KEY, -- 納稅人識別號
qymc VARCHAR(200) NOT NULL, -- 企業名稱
qydh VARCHAR(50) -- 企業電話
) ENGINE=MyISAM CHARSET=utf8;
INSERT INTO yhxx VALUES
('310109040111985', '喬家飲食發展有限公司', '8621-63346626'),
('310104040221736', '上海嘉陵貿易有限公司', '74292546'),
('310108040331576', '翡翠藝術公司', '54861465');
<?php
require_once 'DB.php';
require_once 'XML/Serializer.php';
$dsn = 'mysql://root:pwd@localhost/testdb';
$db = DB::connect($dsn);
if (DB::isError($db)) die($db->getMessage());
$res = $db->query('SELECT * FROM yhxx');
if (DB::isError($res)) die($res->getMessage());
$data = array();
while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
$data[] = $row;
}
$serializer = new XML_Serializer(array(
'rootName' => 'companies',
'recordName' => 'company',
'keyAttribute' => 'id'
));
$serializer->serialize($data);
header('Content-Type: text/xml; charset=utf-8');
echo $serializer->getSerializedData();
?>
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
<xsl:template match="/>
<html><head><title>企業用戶列表</title></head><body>
<table border="1" cellpadding="5" cellspacing="0">
<tr><th>納稅人識別號</th><th>企業名稱</th><th>電話</th></tr>
<xsl:for-each select="companies/company">
<tr>
<td><xsl:value-of select="nsrnm"/></td>
<td><xsl:value-of select="qymc"/></td>
<td><xsl:value-of select="qydh"/></td>
</tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
<?php
// ... 連接資料庫、查詢生成 XML 字串 $xmlStr (同上) ...
$xsl = file_get_contents('browseData.xsl');
$proc = xslt_create();
$html = xslt_process($proc, 'arg:/_xml', 'arg:/_xsl', NULL,
array('/_xml' => $xmlStr, '/_xsl' => $xsl));
if ($html) {
echo $html;
} else {
echo 'XSLT Error: ' . xslt_error($proc) . ' (code ' . xslt_errno($proc) . ')';
}
xslt_free($proc);
?>
PHP 5+ 推薦 DOMDocument + XSLTProcessor (內建 libxml2/libxslt),domxml/xslt 擴展已棄用。現代架構更傾向:
本文作為 XML/XSLT 經典架構歷史參考。