首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 實現 HTML 與 Word 文檔雙向轉換完整指南

     編輯:PHP 綜合知識

前言

辦公自動化場景常需 HTML ⇄ Word 互轉。本文介紹兩種方案:
1. PHP 生成 Word(HTML 另存為 .doc) — 純 PHP,無依賴,適合簡單表格/文本。
2. Word 轉 HTML(COM 組件調用 Word 應用程序) — 需 Windows + Office 安裝,還原度最高。

方案一:PHP 生成 Word 文檔(偽裝 HTML)

利用 Word 能解析特定 XML 命名空間的 HTML 特性,輸出 application/msword 头強制瀏覽器下載。

class WordDocument {
    public function __construct() {
        ob_start();
        echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" ';
        echo 'xmlns:w="urn:schemas-microsoft-com:office:word" ';
        echo 'xmlns="https://www.w3.org/TR/REC-html40">';
        echo '<head><meta charset="UTF-8"></head><body>';
    }
    public function write($html) { echo $html; }
    public function save($filename) {
        echo '</body></html>';
        $content = ob_get_clean();
        header('Content-Type: application/msword');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-Length: ' . strlen($content));
        echo $content;
    }
}

// 使用示例
$doc = new WordDocument();
$doc->write('
<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse">
  <tr><th>姓名</th><th>性別</th><th>年齡</th></tr>
  <tr><td>張三</td><td>男</td><td>32</td></tr>
  <tr><td>李四</td><td>女</td><td>28</td></tr>
</table>
');
$doc->save('用戶列表.doc');

優點: 純 PHP,跨平台,無 Office 依賴。
缺點: 複雜樣式(分頁、頁眉頁腳、圖表)不支持,本質是 HTML 偽裝。

方案二:Word 轉 HTML(COM 組件,Windows + Office 必須)

環境準備

  1. Windows Server / Windows 10 + Microsoft Office (Word)
  2. PHP 啟用 com_dotnet 擴展:
    extension=php_com_dotnet.dll (PHP 7.4+ 需額外安裝)
    com.allow_dcom = true 在 php.ini
  3. Apache/IIS 以具備桌面交互權限的用戶運行(否則 COM 創建失敗)

核心代碼

function word2html(string $wordPath, string $htmlPath): bool {
    if (!file_exists($wordPath)) return false;
    try {
        $word = new COM("Word.Application") or die("無法啟動 Word");
        $word->Visible = false; // 後台運行
        $word->DisplayAlerts = false; // 彈窗靜默
        $doc = $word->Documents->Open(realpath($wordPath), ReadOnly: true);
        // 8 = wdFormatFilteredHTML (較乾淨的 HTML)
        $doc->SaveAs(realpath($htmlPath), 8);
        $doc->Close(false);
        $word->Quit();
        // 釋放 COM 物件
        $doc = null; $word = null;
        return true;
    } catch (com_exception $e) {
        error_log("Word 轉 HTML 失敗: " . $e->getMessage());
        return false;
    }
}

// 調用
word2html('D:/www/test/6.docx', 'D:/www/test/6.html');

常見坑位與解決

問題原因解決
COM 創建失敗 (Class not registered)Office 未安裝或位數不匹配 (PHP x86 vs Office x64)安裝 32 位 Office 或使用 64 位 PHP
頁面長時間無響應Word 進程卡死、彈窗等待設置 Visible=false, DisplayAlerts=false,添加超時監控
轉換出的 HTML 極其臃腫Word 輸出大量 Office 專用標籤使用 tidy 或 DOMDocument 清洗,或改用 LibreOffice headless
併發轉換失敗Word 單進程串行,不支持多實例引入隊列 (Redis/RabbitMQ) 串行處理,或改用 LibreOffice UNO 服務

現代化替代方案推薦

  1. LibreOffice Headless: libreoffice --headless --convert-to html file.docx,Linux/Windows 通用,無 Office 授權成本,適合服務器部署。
  2. PHPWord (PhpOffice): 純 PHP 讀寫 .docx,支持樣式、表格、圖片,適合生成報表。
  3. OnlyOffice / Collabora Online: 網頁端編輯轉換,企業級方案。
  4. Pandoc: 萬能文檔轉換器,命令行調用,格式支持最全。

總結

簡單導出報表 → 方案一(HTML 偽裝 .doc);
需高保真轉換現有 .docx → 方案二(COM)或 LibreOffice Headless;
高併發、跨平台、無 Office 環境 → 僅選 LibreOffice / PHPWord / Pandoc。
切記: 生產環境嚴禁直接在 Web 請求中同步調用 COM 組件,必須異步隊列 + 進程池隔離。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved