PHP method example of automatically adding bom header when downloading files_PHP tutorial

WBOY
Release: 2016-07-13 10:41:25
Original
868 people have browsed it

First of all, let’s figure out what is a bom? 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:

Copy the code The code is as follows:

                                                      Name
$filename = "www.jb51.net.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 message in the result, change the first line of output to the prompt message text
$out = "xEFxBBxBF"; // Add BOM header, 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;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/684745.htmlTechArticleFirst of all, let’s figure out what is a bom? When using a program such as Notepad to save a text file in UTF-8 format under Windows, Notepad will add a few invisible characters (...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!