How to automatically add BOM headers when PHP downloads files

Source: Internet
Author: User
Tags first row

First of all, what is the BOM header? When you save a text file in UTF-8 format with a program like Notepad under Windows, Notepad adds a few invisible characters (the EF BB BF) to the front of the file, which is the so-called BOM (Byte order Mark).

Not limited to Notepad saved files, as long as the openings in the file contain the EF BB BF several invisible characters (16 should be xefxbbxbf, visible with binary editing files). This is like a conventional thing, when the system sees this thing, it will feel that you this file is UTF-8 code.

If your interface is UTF-8, you need to force download a file, such as Csv.excel in the default (Chinese background), that CSV is GB code, so if the meter has a BOM head, then you give the user presented files, may be garbled.

How to add BOM head?

You can add a BOM header before you output the file:

  code is as follows &nbs P;

          & nbsp;    //filename
   $filename = "File.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/; Charset=utf-8 ');
  header (' content-type:text/csv; Charset=utf-8 ');
  header ("content-disposition:attachment; filename={$filename} ");
  //If there is a hint in the result, change the first row output to the prompt message text
   $out = "XEFXBBXBF";//Plus BOM header, The system automatically defaults to the UTF-8 encoding
  if ($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;

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.