1.安装 PHPWord
composer require phpoffice/phpword
2.基础转换代码
require 'vendor/autoload.php'; use PhpOffice\PhpWord\IOFactory; function convertDocxToHtml($inputFile, $outputFile) { // 读取 Word 文档 $phpWord = IOFactory::load($inputFile); // 创建 HTML 写入器 $htmlWriter = new \PhpOffice\PhpWord\Writer\HTML($phpWord); // 保存为 HTML 文件 $htmlWriter->save($outputFile); } // 使用示例 convertDocxToHtml('input.docx', 'output.html');
class CustomHtmlWriter extends \PhpOffice\PhpWord\Writer\HTML { public function writeStyles() { // 添加自定义 CSS $this->writeLn('<style>'); $this->writeLn('body { font-family: Arial, sans-serif; }'); $this->writeLn('h1 { color: #333; }'); $this->writeLn('table { border-collapse: collapse; }'); $this->writeLn('</style>'); } } // 使用自定义写入器 $htmlWriter = new CustomHtmlWriter($phpWord);
function convertDocxToHtmlWithImages($inputFile, $outputFile) { $phpWord = IOFactory::load($inputFile); // 创建临时图片目录 $imagePath = 'images/'; if (!file_exists($imagePath)) { mkdir($imagePath, 0777, true); } // 设置图片保存回调 $htmlWriter = new \PhpOffice\PhpWord\Writer\HTML($phpWord); $htmlWriter->setImageUriCallback(function ($source) use ($imagePath) { $filename = basename($source); copy($source, $imagePath.$filename); return $imagePath.$filename; }); $htmlWriter->save($outputFile); }
function advancedDocxToHtml($inputFile) { $phpWord = IOFactory::load($inputFile); $html = ''; foreach ($phpWord->getSections() as $section) { // 处理页眉 $header = $section->getHeader(); if ($header) { $html .= '<header>'.$header->getText().'</header>'; } // 处理正文元素 foreach ($section->getElements() as $element) { if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) { $html .= '<p>'; foreach ($element->getElements() as $text) { $style = []; $text->getFontStyle() && $text->getFontStyle()->getBold() && $style[] = 'font-weight:bold'; $text->getFontStyle() && $text->getFontStyle()->getItalic() && $style[] = 'font-style:italic'; $html .= sprintf('<span style="%s">%s</span>', implode(';', $style), nl2br($text->getText()) ); } $html .= '</p>'; } elseif ($element instanceof \PhpOffice\PhpWord\Element\Table) { $html .= '<table border="1">'; foreach ($element->getRows() as $row) { $html .= '<tr>'; foreach ($row->getCells() as $cell) { $html .= '<td>'.$cell->getText().'</td>'; } $html .= '</tr>'; } $html .= '</table>'; } } } return $html; } // 输出结果 echo advancedDocxToHtml('document.docx');
格式限制
复杂样式(渐变填充/艺术字等)无法完全保留
建议在转换后手动调整CSS样式
性能优化
大文件处理建议分块读取
启用缓存机制:
\PhpOffice\PhpWord\Settings::setTempDir(sys_get_temp_dir());
编码问题
中文文档需指定编码:
$html = '<meta charset="UTF-8">'.$html;
扩展功能
使用 Dompdf
可将HTML转换为PDF:
composer require dompdf/dompdf $dompdf->loadHtml($html); $dompdf->render();
上传 .docx
文件到服务器
使用 PHPWord 转换为基础HTML
通过正则表达式清理冗余标签
添加自定义CSS样式
输出到浏览器或保存为静态文件
此方案可处理大部分常规文档转换需求,对于复杂格式建议结合前端编辑器(如 CKEditor)进行二次优化。
最新评论: