PHP automatically adds a method instance of the bom header when it downloads a file

  • 2020-12-16 05:52:20
  • OfStack

First of all, what is an bom head? When using a program like Notepad under Windows to save a text file in ES3en-8 format, Notepad prefaces the file header with several invisible characters (EF BB BF), known as BOM (Byte order Mark).
It is not limited to files saved by Notepad, as long as the opening of the file contains several invisible characters of EF BB BF (base 106 should be xEFxBBxBF, edit files visible in base 2). It's kind of a convention, and when the system sees it, it thinks you have es16EN-8.

If your interface is UTF-8, you need to force download a file, such as ES20en.excel. By default, csv is encoded by GB, so if it has bom headers in it, the file you are presenting to the user may be a mess.

How do you add bom headers?
Just add the bom header to the output file:


                //  The file name 
  $filename = "www.ofstack.com.net.csv";

  header('Expires: ' . gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME'] + 10) . ' GMT');
  header('Cache-Control: max-age=10');
  //header('Content-Type: application/vnd.ms-excel; charset=utf-8');
  header('Content-Type: text/csv; charset=utf-8');
  header("Content-Disposition: attachment; filename={$filename}");

  //  If there is a prompt in the result, put the first 1 Line output changed to prompt text 
  $out = "xEFxBBxBF";//  add bom Header, the system automatically defaults to UTF-8 coding 
  if (!empty($extra['notice'])) {
   $out .= "{$extra['notice']}rn";
  }

  //  The output 
  foreach ($table as $row) {
   $out .= implode(",", $row) . "rn";
  }

  /* if (mb_detect_encoding()($out) == 'UTF-8') {
   $out = iconv("UTF-8//IGNORE", "GBK", $out);
  } */
  echo $out;


Related articles: