萬盛學電腦網

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

PHP 生成 Word 文檔的三種方案深度對比:COM、MHT、純 HTML

PHP 生成 Word 文檔主要有三條技術路線:COM 組件調用 Word 應用、生成 MHT (MIME HTML) 格式、直接輸出 HTML 並以 .doc 後綴欺騙瀏覽器。本文深度對比三種方案的原理、代碼實現、優缺點與適用場景。

方案一:COM 組件調用 Microsoft Word (僅限 Windows + Office)

原理

通過 PHP COM 擴展實例化 Word.Application COM 對象,遠程控制 Word 進程生成文檔。

代碼實現

<?php
// 必須啟用 php_com_dotnet.dll (Windows PHP 內建)
$word = new COM("Word.Application") or die("無法啟動 Word: 請確認 Office 已安裝並註冊 COM 組件");
$word->Visible = false;  // 後台運行
$word->DisplayAlerts = false;  // 禁止彈窗

try {
    $doc = $word->Documents->Add();  // 新建文檔
    $word->Selection->TypeText("PHP COM 生成的 Word 文檔\n");
    $word->Selection->TypeText("時間: " . date('Y-m-d H:i:s'));
    
    // 插入表格示例
    $table = $doc->Tables->Add($word->Selection->Range, 3, 3);
    $table->Borders->Enable = true;
    for ($r = 1; $r <= 3; $r++) {
        for ($c = 1; $c <= 3; $c++) {
            $table->Cell($r, $c)->Range->Text = "R{$r}C{$c}";
        }
    }
    
    $savePath = realpath('.') . '/com_generated.docx';
    $doc->SaveAs($savePath, 16);  // 16 = wdFormatXMLDocument (docx)
    echo "生成成功: $savePath";
} catch (com_exception $e) {
    echo "COM 錯誤: " . $e->getMessage();
} finally {
    $word->Quit();
    $word = null;  // 釋放 COM 引用
    // 注意:若腳本異常退出,Word 進程可能殘留,需定時清理
}

優缺點對比

維度評價
功能完整性⭐⭐⭐⭐⭐ 100% Word 功能 (郵件合併、修訂、域、宏、複雜排版)
性能⭐ 極低:啟動 Word 進程 ~2-5秒,單線程,內存佔用大
部署環境❌ 僅 Windows Server + 桌面版 Office (不可用 Server Core)
併發❌ 不支持,需隊列串行
授權⚠️ 需合法 Office 授權,EULA 限制服務器端自動化
維護性❌ 代碼與 Word 版本強耦合,無 IDE 提示,調試困難

結論:不推薦用於 Web 生產環境,僅適合內部低頻報表生成、桌面自動化腳本。

方案二:生成 MHT (MIME HTML) 格式 — 富文本、圖片內嵌、跨平台

原理

MHT (MHTML) 是單文件網頁封裝格式 (RFC 2557),將 HTML + 圖片 (Base64) + CSS 打包為一個 .mht 文件,Word 可原生打開並另存為 .docx。

核心類:MhtFileMaker (簡化版)

<?php
class MhtFileMaker {
    private array $parts = [];
    private string $boundary;
    private string $rootPath = '';
    
    public function __construct() {
        $this->boundary = '----PHP_MHT_BOUNDARY_' . md5(microtime(true));
    }
    
    public function addContent(string $filename, string $contentType, string $content, string $encoding = 'base64'): void {
        $this->parts[] = [
            'filename' => $filename,
            'content_type' => $contentType,
            'content' => $encoding === 'base64' ? base64_encode($content) : $content,
            'encoding' => $encoding,
        ];
    }
    
    public function getFile(): string {
        $header = "From: PHP MHT Generator\n";
        $header .= "Content-Type: multipart/related; boundary=\"{$this->boundary}\"\n\n";
        $header .= "This is a multi-part message in MIME format.\n\n";
        
        $body = '';
        foreach ($this->parts as $part) {
            $body .= "--{$this->boundary}\n";
            $body .= "Content-Type: {$part['content_type']}\n";
            $body .= "Content-Transfer-Encoding: {$part['encoding']}\n";
            $body .= "Content-Location: {$part['filename']}\n\n";
            $body .= $part['content'] . "\n\n";
        }
        $body .= "--{$this->boundary}--\n";
        
        return $header . $body;
    }
    
    public function getMimeType(string $filename): string {
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        return match ($ext) {
            'htm','html' => 'text/html',
            'jpg','jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
            'css' => 'text/css',
            'js' => 'application/javascript',
            default => 'application/octet-stream',
        };
    }
}

高級封裝:getWordDocument() 自動下載圖片並生成 MHT

<?php
function getWordDocument(string $html, string $baseUrl = '', bool $removeLinks = true): string {
    $mht = new MhtFileMaker();
    
    // 1. 可選移除鏈接
    if ($removeLinks) {
        $html = preg_replace('/(.*?)<\/a>/is', '$1', $html);
    }
    
    // 2. 提取所有圖片
    $images = [];
    if (preg_match_all('/]+src=["\']([^"\']+)["\']/i', $html, $matches)) {
        foreach ($matches[1] as $i => $src) {
            $src = trim($src);
            if ($src === '') continue;
            
            // 處理相對路徑
            if (strpos($src, 'https://') !== 0 && strpos($src, 'https://') !== 0) {
                $src = rtrim($baseUrl, '/') . '/' . ltrim($src, '/');
            }
            
            // 下載圖片
            $imgContent = @file_get_contents($src);
            if ($imgContent === false) continue;
            
            $ext = pathinfo(parse_url($src, PHP_URL_PATH), PATHINFO_EXTENSION) ?: 'jpg';
            $filename = "image_{$i}.{$ext}";
            
            $mht->addContent($filename, $mht->getMimeType($filename), $imgContent);
            $images[$matches[0][$i]] = $filename;  // 記錄原標籤→本地文件名映射
        }
    }
    
    // 3. 重寫 HTML 中圖片路徑為 CID 格式
    foreach ($images as $originalTag => $filename) {
        $html = str_replace($originalTag, str_replace(
            $matches[1][array_search($originalTag, $matches[0])],  // 簡化:實際需更精確替換
            "cid:{$filename}",
            $originalTag
        ), $html);
    }
    
    // 4. 添加主 HTML 部分
    $mht->addContent('content.html', 'text/html; charset=utf-8', $html, 'base64');
    
    return $mht->getFile();
}

// 使用
$html = file_get_contents('https://example.com/article/123');
$mhtContent = getWordDocument($html, 'https://example.com');
file_put_contents('article.doc', $mhtContent);  // 以 .doc 後綴,Word 可直接打開

方案三:直接輸出 HTML 並偽裝為 .doc (最簡單、兼容性最好)

原理

Word 可直接打開 HTML 文件,只需設置正確的 HTTP Header 欺騙瀏覽器/Word 以 Word 文檔方式處理。

實現代碼

<?php
function outputHtmlAsWord(string $html, string $filename = 'document.doc'): void {
    // 關鍵 Header
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    header("Content-Type: application/msword");  // 或 application/vnd.ms-word
    header("Content-Disposition: attachment; filename=\"" . rawurlencode($filename) . "\"");
    header("Content-Length: " . strlen($html));
    
    // 輸出 HTML 內容 (需包含完整 ......)
    echo $html;
    exit;
}

// 使用示例
$wordHtml = <<


    
    


    

PHP 生成 Word 文檔演示

生成時間:

項目值
項目 A100
項目 B200

Logo

HTML; outputHtmlAsWord($wordHtml, '報表_' . date('Ymd') . '.doc');

三大方案綜合對比

維度COM (Word 自動化)MHT (MIME HTML)HTML 偽裝 .doc
跨平台❌ 仅 Windows✅ 全平台✅ 全平台
依賴Office + COM 擴展純 PHP純 PHP
併發能力極差 (串行)優 (無狀態)優 (無狀態)
排版精度完美 (原生渲染)良好 (Word 解析 HTML)一般 (Word 解析 HTML)
圖片內嵌原生插入Base64 內嵌 (MHT)外部鏈接 (需網絡) 或 Base64 Data URI
複雜結構 (目錄、引用、域)✅ 完整支持❌ 不支持❌ 不支持
文件大小標準大 (Base64 +33%)小
推薦場景內部複雜報表、郵件合併離線文檔、需內嵌圖片、跨平台Web 導出、簡單報表、高併發、無 Office 環境

現代化替代方案:PHPWord / PhpOffice

<?php
// composer require phpoffice/phpword
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;

$phpWord = new PhpWord();
$section = $phpWord->addSection();

$section->addText('PHPWord 生成真正的 DOCX', ['bold' => true, 'size' => 16]);
$section->addTextBreak(2);

$table = $section->addTable(['borderSize' => 6, 'borderColor' => '000000']);
$table->addRow();
$table->addCell(3000)->addText('列 1');
$table->addCell(3000)->addText('列 2');
$table->addRow();
$table->addCell()->addText('數據 A');
$table->addCell()->addText('數據 B');

$writer = IOFactory::createWriter($phpWord, 'Word2007');
$writer->save('phpword_generated.docx');

PHPWord 優勢:生成真正的 OOXML (docx)、純 PHP 跨平台、支持樣式/表格/圖片/頁眉頁腳/目錄/水印、活躍維護、Composer 安裝。

總結選型建議

  1. 95% Web 場景:PHPWord (PhpOffice) — 真正的 docx、跨平台、功能豐富、現代化
  2. 極簡導出、無依賴要求:HTML 偽裝 .doc — 零依賴、高併發、樣式受限
  3. 需離線閱讀、內嵌圖片、無 Office 環境:MHT — 單文件封裝、Word 原生打開
  4. 極複雜排版、郵件合併、宏、修訂、僅 Windows 內網:COM — 最後手段

拒絕 COM 自動化進入 Web 生產環境,擁抱 PHPWord 或 HTML 導出,構建現代化、可擴展的文檔生成服務。

copyright © 萬盛學電腦網 all rights reserved