简体   繁体   中英

PHP to CSV output to download

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-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 have the Content-Type correctly set, and indeed it is probably misleading the browser into thinking it has received a binary file as well:

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

Update:

I see another problem. You are setting the Content-Length not to the size of the file, but rather to the file handle opened by fopen() , 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 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM