萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 輸出 XML 與 Word 文檔:DOMDocument、HTTP Header 與 COM 元件三種方案

方案一:原生字串拼接 XML(簡單、無依賴)

<?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>';

⚠️ 易出現編碼問題、實體未轉義,不推薦生產環境。

方案二:DOMDocument 物件導向(標準、健壯)

$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。

方案三:輸出 Word 文檔(.doc)

方法 A:HTML 偽裝 .doc(跨平台、無依賴)

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 打開可正常顯示表格樣式。

方法 B:COM 元件自動化(僅 Windows、需安裝 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 進程佔用大量記憶體、易卡死、併發極差、授權成本高。

現代替代方案推薦

  • PHPWord (PhpOffice\PhpWord):純 PHP 生成 .docx/.odt,支援樣式、表格、圖片、頁首尾。
    composer require phpoffice/phpword
  • XML/JSON API + 前端匯出:後端只提供數據,前端用 SheetJS、Docxtemplater 或瀏覽器原生下載生成文件。
copyright © 萬盛學電腦網 all rights reserved