The snippet reads an ouput stream in a new file CSV. That part works. I can open the file from the server and it looks perfect. The problem is with the file which downloads to my hard drive through the browser. It will not open and read properly in spreadsheet software or Excel on a Windows machine:
$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);
The content of the CSV looks ��ࡱ� like when I open it from the browser download but looks perfect when I open it directly on the server or download the stored file with FTP.
The browser sees the
application/octet-streamas a binary type. You need atext/plaincontent type:The
Content-Transfer-Encodingheader should be unnecessary if you have theContent-Typecorrectly set, and indeed it is probably misleading the browser into thinking it has received a binary file as well:###Update:
I see another problem. You are setting the
Content-Lengthnot to the size of the file, but rather to the file handle opened byfopen(), which mis-informs the browser of the number of bytes to expect.filesize()takes a string filename as its argument, not a file handle. You will probably need to close the handle withfclose($NewFile)before callingfilesize().