PHP 到 CSV 输出下载

标签 php csv

该片段读取新文件 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/

相关文章:

php - 运行 "unable to find the application log"后如何抑制警告 "symfony serve"?

javascript - 当模式框关闭时,如何将我的复选框重置为未选中状态?

Python - 如何使用多个分隔符拆分列值

MySQL 将多个表中的特定字段导出到一个 csv 文件中?创建表输出

php - Xdebug Profiler 无法在 apache 上工作

php - 在 Laravel 5 中扩展 SQLite 蓝图

php - 访问父变量

csv - 如何将 CSV 文件中的股票数据读取到 netlogo 中?

csv - 将应用程序移动到新服务器后,使用 CsvHelper 库生成的 CSV 文件中缺少逗号/分隔符

python - 快速删除大型 .csv 文件中的 header