I';我在使用PHP header()时得到一个找不到文件的错误


I'm getting a file not found error when using PHP header()

我有一个php文件,用于CSV下载。

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=users.csv');
echo $csvOut;

其中$csvOut是我在另一个函数中生成的字符串。

问题是,当我导航到这个PHP文件时,浏览器会给我一个404文件未找到错误。当我删除header('Content-Disposition: attachment;filename=users.csv');行时,它也会做同样的事情。

然而,我注意到,如果我将header('Content-Type: text/csv');更改为header('Content-Type: text/html');,它会在屏幕上显示$csvOut的内容,但前提是header('Content-Disposition: attachment;filename=users.csv');已被删除。

这真的让我很困惑,因为我以前已经成功地使用了这个代码来提供CSV文件,我看不出我在做什么(或没有做什么),这会破坏它

如有任何帮助,我们将不胜感激!

你试过这个吗:

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=users.csv');
echo $csvOut;
exit(); //Stop script from processing anything else and this will trigger the download

希望这能帮助

请先尝试设置200 OK响应。我不知道为什么Content-Type和/或Content-Disposition标头在文件实际存在时返回一个找不到的404,但它使我的脚本开始下载,所以它可能也适用于您:

<?php
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=users.csv');
echo file_get_contents($csvOut);
exit();