【问题标题】:PHP to CSV output to downloadPHP转CSV输出下载
【发布时间】:2012-08-30 01:26:16
【问题描述】:

sn-p 读取新文件 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 下载存储的文件时看起来很完美。

【问题讨论】:

  • 您是否尝试过通过浏览器阅读,而不是尝试下载?这可以告诉您是您的文件被浏览器弄乱了,还是您的下载代码损坏了某些东西。
  • 既然是 csv,编码不应该是 Content-Type: text/plain 甚至是 text/csv
  • @AdrianCornish 我相信你是对的。作为一个纯文本文件,不管它的扩展名和程序如何解释它,它只是文本,应该相应地保存。

标签: php csv


【解决方案1】:

浏览器将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 标头,实际上它可能会误导浏览器认为它也收到了二进制文件:

// 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));

【讨论】:

  • 我尝试过 application/csv 和 text/csv - 没有尝试过 text/plain 但会。
  • 我会尝试使用 header('Content-Type: text/csv; charset=utf-8');
  • 我想我现在只是在尝试并没有坚持我的知识 - 可能明天应该再次拿起它,但这是我完成这个插件所需的最后一件事。根据我们在这里所说的,我现在有:$NewFile = fopen($FileName,"w"); fwrite($NewFile, $output); header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="'.$FileName.'"'); fclose($NewFile); header('Content-Length: '.filesize($FileName)); 同样的结果。服务器上的文件很好,但浏览器不是。我开始怀疑 .htaccess 文件或配置中是否有某些内容。
  • 这是您可以阅读的有关编码的文档,因为我知道这是编码问题:webmonkeyuk.wordpress.com/2011/04/23/…
  • 谢谢大家。我想我只需要休息一下,明天再打开它。我同意@JonathanLaf 的观点,它在输出到浏览器时看起来像是一个编码问题。
猜你喜欢
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多