Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要下载的PHP到CSV输出_Php_Csv - Fatal编程技术网

要下载的PHP到CSV输出

要下载的PHP到CSV输出,php,csv,Php,Csv,该代码段读取新CSV文件中的输出流。那部分有效。我可以从服务器打开文件,它看起来很完美。问题在于通过浏览器下载到硬盘的文件。在Windows计算机上,它无法在电子表格软件或Excel中正确打开和读取: $NewFile = fopen($FileName,"w"); fwrite($NewFile, $output); header('Content-Description: File Transfer'); header('Content-Type: application/octet-str

该代码段读取新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下载存储的文件时,它看起来非常完美。

浏览器将
应用程序/octet流
视为二进制类型。您需要
text/plain
内容类型:

header('Content-Type: text/plain');
// Or:
header('Content-Type: text/csv');
// Or: 
header('Content-Type: application/csv');
如果正确设置了
内容类型
,则
内容传输编码
标题应该是不必要的,事实上,这可能会误导浏览器认为它也收到了二进制文件:

// No need, possibly harmful. Remove it...
// header('Content-Transfer-Encoding: binary');
更新: 我看到另一个问题。您将
内容长度设置为
fopen()
打开的文件句柄,而不是文件大小,该句柄会错误地通知浏览器预期的字节数。将字符串文件名作为其参数,而不是文件句柄。在调用
filesize()
之前,可能需要使用
fclose($NewFile)
关闭句柄


您是否尝试过通过浏览器阅读,而不尝试下载?这可能会告诉你是你的文件被你的浏览器弄乱了,还是你的下载代码正在破坏某些东西。因为它是csv,所以编码不应该是
内容类型:text/plain
,甚至
text/csv
@AdrianCornish,我相信你是对的。作为一个纯文本文件,不管它的扩展名和程序如何解释它,它都是文本,应该相应地保存。我尝试了application/csv和text/csv-没有尝试text/plain,但会尝试使用header('Content-Type:text/csv;charset=utf-8');我想我现在只是在尝试,而不是坚持我的知识-也许明天应该再次学习,但这是我完成这个插件的最后一件事。根据我们在这里所说的,我现在有:
$NewFile=fopen($FileName,“w”);fwrite($NewFile,$output);标题('Content-Type:text/csv;charset=utf-8');标题('Content-Disposition:attachment;filename=“.”.$filename.'”);fclose($NewFile);标题('Content-Length:'.filesize($FileName))相同的结果。服务器上的文件正常,但浏览器不正常。我开始怀疑.htaccess文件或配置中是否有什么内容。这里有一个关于编码的文档,您可以阅读,因为,到目前为止,我知道这是一个编码问题:谢谢大家。我想我需要休息一下,明天再打开它。我同意@JonathanLaf的观点,它在输出到浏览器时似乎存在编码问题。
// Instead of:
header('Content-Length: ' . filesize($NewFile));

// You mean to use $FileName
// close the file handle first...
fclose($NewFile);
header('Content-Length: ' . filesize($FileName));