使用 php 从服务器下载后 docx 文件已损坏

Cre*_*ema 5 php download docx readfile

我正在尝试使用 php 从服务器下载 Word 文档(.docx)。不幸的是我得到的文件已损坏。我可以用 word 打开文档,但我收到这些恼人的消息(文件已损坏等)。这是我的代码:

$file = "documents/".$_POST["id_form"]."_document.docx";
$filename = $_POST["id_form"]."_document.docx";
header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
header("Content-Disposition: attachment; filename=".$filename);

readfile($file);
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助!

更新解决方案

我得到了解决方案。我必须把ob_end_clean();在标题和出口之前;在 readfile($file) 之后。现在效果很好。

这是工作代码:

    $file = "documents/".$_POST["id_form"]."_document.docx";
    $filename = $_POST["id_form"]."_document.docx";                 
    ob_end_clean();
    header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    header("Content-Disposition: attachment; filename=".$filename);
    readfile($file);
    exit;
Run Code Online (Sandbox Code Playgroud)