该片段读取新文件 CSV 中的输出流。那部分有效。我可以从服务器打开文件,它看起来很完美。问题在于通过浏览器下载到我的硬盘的文件。它无法在 Windows 计算机上的电子表格软件或 Excel 中正确打开和读取:
$NewFile = fopen($FileName,"w");
fwrite($NewFile, $output);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$FileName.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($NewFile));
ob_clean();
flush();
readfile($NewFile);
当我从浏览器下载打开它时,CSV 的内容看起来很像,但当我直接在服务器上打开它或使用 FTP 下载存储的文件时看起来很完美。
最佳答案
浏览器将 application/octet-stream
视为二进制类型。您需要一个 text/plain
内容类型:
header('Content-Type: text/plain');
// Or:
header('Content-Type: text/csv');
// Or:
header('Content-Type: application/csv');
如果您正确设置了Content-Type
,那么Content-Transfer-Encoding
header 应该是不必要的,实际上它可能会误导浏览器认为它已经收到还有一个二进制文件:
// No need, possibly harmful. Remove it...
// header('Content-Transfer-Encoding: binary');
更新:
我看到另一个问题。您将 Content-Length
设置为不是文件的大小,而是设置为 fopen()
打开的文件句柄,这会错误地告知浏览器数字期望的字节数。 filesize()
将字符串文件名作为其参数,而不是文件句柄。在调用 filesize()
之前,您可能需要使用 fclose($NewFile)
关闭句柄。
// Instead of:
header('Content-Length: ' . filesize($NewFile));
// You mean to use $FileName
// close the file handle first...
fclose($NewFile);
header('Content-Length: ' . filesize($FileName));
关于PHP 到 CSV 输出下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12188702/