Exit PHP to CSV for download

Snapshots read the output stream in a new CSV file. This part works. I can open the file from the server and it looks perfect. The problem is with the file that is downloaded to my hard drive through the browser. It will not open and will not be correctly read in the program for working with spreadsheets or Excel on a computer running Windows:

$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 content looks like, for example, when I open it from the browser download, but it looks perfect when I open it directly on the server or download the saved file from FTP.

+4
source share
1 answer

The browser sees application/octet-stream as a binary type. You need a text/plain content type:

 header('Content-Type: text/plain'); // Or: header('Content-Type: text/csv'); // Or: header('Content-Type: application/csv'); 

The Content-Transfer-Encoding header should be unnecessary if you installed the Content-Type correctly, and indeed, it is likely to mislead the browser, thinking that it received the binary:

 // No need, possibly harmful. Remove it... // header('Content-Transfer-Encoding: binary'); 

Update:

I see another problem. You set the Content-Length not the file size, but rather the file descriptor opened with fopen() , which incorrectly informs the browser about the number of bytes expected. filesize() takes the file name string as its argument, not a file descriptor. You probably need to close the handle with fclose($NewFile) before calling filesize() .

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

All Articles