You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用PhpWord生成带批注文档出现重复comments.xml文件问题

解决PhpWord生成带批注Word文档的不可读内容警告问题

问题根源

你遇到的警告是因为代码中重复添加了批注,同时缺少批注范围的结束标记,导致生成的docx包中出现重复的comments.xml内容(一个是手动添加的无关联范围批注,另一个是关联文本范围的批注),触发Word的格式校验警告。

修复步骤

  1. 移除手动添加批注的代码行
    删除$phpWord->addComment($comment);这一行。当你通过setCommentRangeStart将批注关联到文本范围时,PhpWord会自动负责将批注加入文档,手动调用addComment会产生无关联的重复批注,导致文件结构异常。

  2. 补充批注范围的结束标记
    批注需要明确的起始和结束范围,仅设置CommentRangeStart会导致Word认为批注结构不完整。在文本范围的末尾元素上添加setCommentRangeEnd标记。

修复后的完整代码

<?php
ob_start(); // 开启输出缓冲
require_once('bootstrap.php');

// 创建新文档
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->getCompatibility()->setOoxmlVersion(15);

// 添加空白章节
$section1 = $phpWord->addSection();

// 创建批注
$comment = new \PhpOffice\PhpWord\Element\Comment('Authors name');
$comment->addText('Test comment', ['bold' => true]);

// 创建文本块并关联批注范围
$textrun = $section1->addTextRun();
$textrun->addText('This ');
$textStart = $textrun->addText('is');
$textStart->setCommentRangeStart($comment); // 批注起始标记
$textEnd = $textrun->addText(' a test');
$textEnd->setCommentRangeEnd($comment); // 批注结束标记
                        
ob_clean();

$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');

// 可选:若PCLZIP仍有问题,可尝试默认的ZipArchive(注释掉下面一行即可)
// \PhpOffice\PhpWord\Settings::setZipClass(\PhpOffice\PhpWord\Settings::PCLZIP);

// 保存文档
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($temp_file);

// 输出下载头
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="duplicates.docx"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');

readfile($temp_file); 
unlink($temp_file); // 清理临时文件(原代码中的file_get_contents无意义,建议替换为删除临时文件)
?>

额外说明

  • 原代码中的file_get_contents($temp_file);没有实际作用,建议替换为unlink($temp_file);来清理临时文件,避免服务器磁盘占用。
  • 若仍有问题,可以尝试移除setZipClass的设置,使用PhpWord默认的ZipArchive类,部分环境下PCLZIP可能会有文件打包的兼容性问题。

内容的提问来源于stack exchange,提问作者Doom_Cat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:18:20