php downloads a solution that excel could not open

  • 2020-11-26 18:44:34
  • OfStack

php Download the excel file,
1. Do not output any non-file information, such as echo log, during the downloading process. Otherwise, the downloaded file cannot be opened, indicating that the format is wrong or the file is corrupted.
2. The output of excel format 1 must be 1 straight with the suffix name, or it will prompt the format error or the file is destroyed


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: no production file ');
      echo '<script>alert(\'export error, file not exists ! \')</script>';
  }


Related articles: