PHP automatically adds the bom header when downloading files

Source: Internet
Author: User

First, find out what is the bom header? When you save a text file in UTF-8 format with a program such as Notepad in Windows, notepad will add a few invisible characters (ef bb bf) before the file header ), is the so-called BOM (Byte order Mark ).
It is not limited to files stored in Notepad, as long as the file's opening contains several invisible characters of ef bb bf (the hexadecimal format should be xEFxBBxBF, which can be seen by binary editing files ). This is like a convention, and when the system sees it, it will feel that your file is UTF-8-encoded.

If your interface is UTF-8, you need to force download a file, such as csv. excel considers csv as GB encoded by default (in Chinese), so if the rice has a bom header, the file you present to the user may be garbled.

How can I add a bom header?
Add the bom header before the output file:

The code is as follows: Copy code

// File name
$ 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/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, change the first line of output to the prompt text.
$ Out = "xEFxBBxBF"; // with the bom header added, the system automatically defaults to UTF-8 encoding
If (! Empty ($ extra ['notice']) {
$ Out. = "{$ extra ['notice']} rn ";
  }
 
// 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 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: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.