PHP到CSV输出下载
发布时间:2020-12-13 16:17:59 所属栏目:PHP教程 来源:网络整理
导读:该片段在新文件CSV中读取输出流.那部分有效.我可以从服务器打开文件,看起来很完美.问题是通过浏览器下载到我的硬盘驱动器的文件.它无法在 Windows机器上的电子表格软件或Excel中正确打开和读取: $NewFile = fopen($FileName,"w");fwrite($NewFile,$output);
该片段在新文件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标头应该是不必要的,事实上它可能误导浏览器认为它也收到了二进制文件: // No need,possibly harmful. Remove it... // header('Content-Transfer-Encoding: binary'); 更新: 我看到了另一个问题.您将Content-Length设置为不是文件的大小,而是设置为fopen()打开的文件句柄,这会错误地通知浏览器预期的字节数. // Instead of: header('Content-Length: ' . filesize($NewFile)); // You mean to use $FileName // close the file handle first... fclose($NewFile); header('Content-Length: ' . filesize($FileName)); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |