<?php
header("Content-Type: text/xml; charset=utf-8");
echo '<?xml version="1.0" encoding="utf-8"?>';
echo '<schema>';
foreach ($tables as $table) {
echo "<table name=\"$table\">";
$result = mysql_query("SHOW FIELDS FROM `$table`");
while ($row = mysql_fetch_row($result)) {
echo "<field name=\"{$row[0]}\" type=\"{$row[1]}\"";
echo ($row[3] === 'PRI') ? ' primary_key="yes" />' : ' />';
}
echo '</table>';
}
echo '</schema>';
⚠️ 易出現編碼問題、實體未轉義,不推薦生產環境。
$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = true; // 縮進美化
$schema = $dom->createElement('schema');
$dom->appendChild($schema);
foreach ($tables as $table) {
$tableNode = $dom->createElement('table');
$tableNode->setAttribute('name', $table);
$schema->appendChild($tableNode);
$result = mysql_query("SHOW FIELDS FROM `$table`");
while ($row = mysql_fetch_row($result)) {
$field = $dom->createElement('field');
$field->setAttribute('name', $row[0]);
$field->setAttribute('type', $row[1]);
if ($row[3] === 'PRI') $field->setAttribute('primary_key', 'yes');
$tableNode->appendChild($field);
}
}
echo $dom->saveXML();
優點:自動實體轉義、結構驗證、支援 XPath/XSLT。
header("Content-Type: application/vnd.ms-word");
header("Content-Disposition: attachment; Filename=report.doc");
header("Pragma: no-cache");
header("Expires: 0");
?>
<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word">
<head><meta charset="utf-8"></head>
<body>
<h1>報表標題</h1>
<table border="1"><tr><th>欄位</th><th>值</th></tr>
<?php foreach ($data as $row): ?>
<tr><td><?= $row['name'] ?></td><td><?= $row['value'] ?></td></tr>
<?php endforeach; ?>
</table>
</body></html>
瀏覽器會提示下載 .doc,Word 打開可正常顯示表格樣式。
try {
$word = new COM("Word.Application") or die("無法啟動 Word");
$word->Visible = false;
$doc = $word->Documents->Add();
$doc->PageSetup->LeftMargin = $doc->PageSetup->RightMargin = 72; // 2.54cm
$doc->Content->Font->Name = '微軟正黑體';
$doc->Content->Font->Size = 12;
$doc->Content->InsertAfter("報表內容\n\n");
$table = $doc->Tables->Add($doc->Range, count($data)+1, 2);
$table->Borders->Enable = true;
// 填充表頭...
$tmp = tempnam(sys_get_temp_dir(), 'word_') . '.docx';
$doc->SaveAs($tmp, 16); // 16 = wdFormatXMLDocument (docx)
$doc->Close(false);
$word->Quit();
unset($word);
header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
header("Content-Disposition: attachment; Filename=report.docx");
readfile($tmp);
unlink($tmp);
} catch (com_exception $e) {
echo "COM 錯誤: " . $e->getMessage();
}
⚠️ 生產環境極不推薦:Word 進程佔用大量記憶體、易卡死、併發極差、授權成本高。
composer require phpoffice/phpword