若需在 Linux/Windows 伺服器完美還原 Word 排版(含複雜表格、浮水印、公式、SmartArt),唯有呼叫真正的 Microsoft Word 引擎。本文介紹 Windows + PHP COM 擴充套件啟動 Word Application 另存為 HTML 的完整流程,並說明 LibreOffice/WPS 方案的局限。
com_dotnet 擴充:php.ini 取消註解 extension=php_com_dotnet.dll 並設 com.allow_dcom = true<?php
function word2html(string $wordPath, string $htmlPath): bool {
if (!file_exists($wordPath)) return false;
try {
$word = new COM("Word.Application") or die("無法啟動 Word");
$word->Visible = 0; // 無頭模式
$word->DisplayAlerts = 0; // 關閉彈窗
$doc = $word->Documents->Open(realpath($wordPath), ReadOnly: true);
// wdFormatFilteredHTML = 10, wdFormatHTML = 8
$doc->SaveAs($htmlPath, 8);
$doc->Close(false);
$word->Quit();
$word = null;
unset($word);
// 釋放 COM 參考
while (com_release($word) > 0) {}
return file_exists($htmlPath);
} catch (com_exception $e) {
error_log("Word 轉換失敗: " . $e->getMessage());
return false;
}
}
// 使用
word2html('D:/www/test/6.docx', 'D:/www/test/6.html');
| SaveAs 格式常數 | 值 | 用途 |
|---|---|---|
| wdFormatHTML | 8 | 標準 HTML,含 Office 專屬標籤 |
| wdFormatFilteredHTML | 10 | 過濾 Office 標籤,較乾淨但可能遺失部分樣式 |
$word->DisplayAlerts = 0、確保 Word 已完成首次啟動授權、檔案無密碼保護。<o:p>、<w:...> 標籤。後續可用 tidy 或自訂正則清洗。| 方案 | 排版還原度 | 環境 | 併發 | 維護成本 |
|---|---|---|---|---|
| PHP COM + MS Word | ★★★★★ | Windows | 低(串行) | 高(需授權、桌面權限) |
| LibreOffice Headless | ★★★☆☆ | Linux/Win | 高(多進程) | 低(開源免費) |
| 第三方 API (Aspose, CloudConvert) | ★★★★☆ | 雲端 | 高 | 按量付費 |
| PHPWord (純 PHP 讀取) | ★★☆☆☆ | 跨平台 | 高 | 低 |
生產環境建立「轉換微服務」:API 接收上傳 → 存入暫存 → 推入 Redis/RabbitMQ 佇列 → Worker 串行呼叫 COM → 結果回調/輪詢 → 回傳 HTML URL。並設定超時殺進程、磁碟空間監控、Word 進程定期重啟防記憶體洩漏。