PHP generate UTF-8 encoded CSV file with Excel open garbled solution

Source: Internet
Author: User
Cause: There is no BOM in the output CSV file.

What is a BOM?

There is a character called "ZERO WIDTH no-break SPACE" in the UCS encoding, and its encoding is Feff. Fffe is not a character in UCS, so it should not appear in the actual transmission. The UCS specification recommends that the character "ZERO WIDTH no-break SPACE" be transmitted before the byte stream is transmitted. This means that if the recipient receives Feff, the byte stream is Big-endian, and if Fffe is received, it indicates that the byte stream is Little-endian. So the character "ZERO WIDTH no-break SPACE" is also called a BOM.

The UTF-8 does not require a BOM to indicate byte order, but it can be used to indicate the encoding using a BOM. The UTF-8 code for the character "ZERO WIDTH no-break SPACE" is the EF BB BF. So if the receiver receives a byte stream beginning with the EF BB BF, it knows that this is UTF-8 encoded.

Windows uses a BOM to mark the way a text file is encoded.

How do I output a BOM in PHP?

Before all content is output

Print (Chr (0xEF). chr (0xBB). Chr (0xBF));

Example code:

<?php    function Writecsvtofile ($file, array $data) {        $fp = fopen ($file, ' W ');        Use BOM to mark the encoding of text files under Windows        fwrite ($fp, Chr (0xEF). chr (0xBB). Chr (0xBF));        foreach ($data as $line) {            fputcsv ($fp, $line);        }        Fclose ($FP);    }
  • 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.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.