Home > Backend Development > PHP Tutorial > PHP method to automatically add BOM header when downloading files, _PHP tutorial

PHP method to automatically add BOM header when downloading files, _PHP tutorial

WBOY
Release: 2016-07-12 08:59:46
Original
1069 people have browsed it

How to automatically add BOM header when downloading files in PHP.

First of all, figure out what is BOM header? When you use a program such as Notepad to save a text file in UTF-8 format under Windows, Notepad will add a few invisible characters (EF BB BF) in front of the file header, which is the so-called BOM (Byte order Mark). ).
Not limited to files saved in Notepad, as long as the opening of the file contains several invisible characters EF BB BF (hexadecimal should be xEFxBBxBF, visible when editing the file in binary). This is like a convention. When the system sees this thing, it will think that your file is UTF-8 encoded.

If your interface is UTF-8, you need to force download a file, such as csv.excel by default (Chinese background), considers csv to be GB encoded, so if there is a BOM header, then you can The file presented by the user may be garbled.

How to add bom?
Just add the bom header before the output file:

The code is as follows Copy the code
                                                   

    // 文件名
  $filename = "www.111cn.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}");
  
  // 如果结果中有提示信息,则把第一行输出改为提示信息文字
  $out = "xEFxBBxBF";// 加上bom头,系统自动默认为UTF-8编码
  if (!empty($extra['notice'])) {
   $out .= "{$extra['notice']}rn";
  }
 
  // 输出
  foreach ($table as $row) {
   $out .= implode(",", $row) . "rn";
  }
  
  /* if (mb_detect_encoding()($out) == 'UTF-8') {
   $out = iconv("UTF-8//IGNORE", "GBK", $out);
  } */
  echo $out;
Copy after login
 

http://www.bkjia.com/PHPjc/1096607.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1096607.htmlTechArticlePHP How to automatically add BOM header when downloading files. First, figure out what is BOM header? When you use a program like Notepad to save a text file in UTF-8 format under Windows, Notepad will...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template