Php download excel files cannot be opened
Solutions and precautions for php excel files that cannot be opened after being downloaded
Php downloads excel files,
1. Do not output any non-file information, such as echo log information, during the download process. Otherwise, the downloaded file cannot be opened and the system prompts that the format is incorrect or the file is damaged.
2. The output excel format must be kept with the suffix. If not, an error message is displayed, or the file is damaged.
The Code is as follows:
If (file_exists (CACHE_PATH. $ file_name )){
// $ This-> logger-> error ('file realpath: '. realpath (CACHE_PATH. $ file_name ));
Header ('pragma: public ');
Header ('expires: 0 ');
Header ('content-Encoding: none ');
Header ('cache-Control: must-revalidate, post-check = 0, pre-check = 0 ');
Header ('cache-Control: public ');
Header ('content-Type: application/vnd. ms-excel ');
Header ('content-Description: File Transfer ');
Header ('content-Disposition: attachment; filename = '. $ file_name );
Header ('content-Transfer-Encoding: binary ');
Header ('content-Length: '. filesize (CACHE_PATH. $ file_name ));
Readfile (CACHE_PATH. $ file_name );
} Else {
$ This-> logger-> error ('export model: '. $ id.' error: file not produced ');
Echo '<script> alert ('export error, file not exists! ') </Script> ';
}