我正在尝试使用“PHPWord”下载 docx 文件。
如果我尝试将文件保存到服务器上,它工作正常。但是,如果添加 header 来下载它,那么该文件将以损坏的形式显示。
注意:我使用 openOffice 打开它。
这是我的代码:
$document->save($doc);
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header("Content-Disposition: attachment; filename=CV.docx");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($doc));
readfile($doc);
谁能告诉我问题出在哪里吗?
最佳答案
让我猜一下:
您的程序在发送 header
之前输出一些文本(如果您不手动回显
某些内容,它可能会是一个 php 警告,也算作输出)。因此,在文件的实际输出中,如果您使用简单的文本编辑器将其打开为 txt
(只需将扩展名重命名为 .txt
并使用记事本打开它),第一个行将类似于:
警告:无法修改 header 信息 - header 已由/some/file.php 第 23 行(输出从/some/file.php:12 开始)发送
...然后是 doc
文件的其余部分。当然,这是损坏的。
如果是这种情况,您不应在 header
之前输出任何内容
关于php - 使用 PHPWord 下载 DOCX 文件时出现损坏的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25883886/