Download Excel From Server Using PHP

2019-08-31 01:51发布

Can anyone help me to write code on PHP to download Excel File from the server.

I have created below codes using header and readfile but the downloaded file was corrupted.

//content type
header('Content-type: application/vnd.ms-excel');
//open/save dialog box
header('Content-Disposition: attachment; filename='.$fileName);
//read from server and write to buffer
readfile($reportPath);

Can anyone help me on the best way to download existing Excel file from the server.

Please see below image of data after downloadedenter image description here

3条回答
Evening l夕情丶
2楼-- · 2019-08-31 02:08

I suggest to use the X-SENDFILE header. https://tn123.org/mod_xsendfile/

查看更多
聊天终结者
3楼-- · 2019-08-31 02:12

I use something like the following:

header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Length: ".filesize($path));
readfile($path);
exit;

Make sure you're not outputting anything before or after the readfile.

查看更多
贪生不怕死
4楼-- · 2019-08-31 02:31
ob_clean();

put that code before all header declaration

查看更多
登录 后发表回答