I want to create a CSV with UTF-8, but ANSI outputs it.

Asked 2 years ago, Updated 2 years ago, 134 views

I would like to create a CSV with the character code UTF-8 in PHP 5.4 (Cakephp2 environment), but when I look at the character code I printed in Notepad, it looks like ANSI.How can I fix it?Thank you for your cooperation.

<?php
class HelloShell extensions AppShell {
    public function main()
    {
        header('Content-Type: application/octet-stream; charset=UTF-8');
        $array=array(mb_convert_encoding("Windows", "UTF-8"),
            mb_convert_encoding("Mac", "UTF-8"),
            mb_convert_encoding("Linux", "UTF-8")
        );

        $file=fopen("test.csv", "w");
        if($file){
            var_dump(fputcsv($file,$array)));
        }
        fclose($file);
    }
}

php cakephp

2022-09-30 21:39

2 Answers

This is probably because the BOM indicating UTF-8 is not written at the beginning of the file.
How to create a CSV that prevents garbled characters in PHP Excel
Why don't you add it before writing CSV data as follows?

if($file){
            fwrite($file, '\xEF\xBB\xBF');
            var_dump(fputcsv($file,$array)));
        }

Note)
As you commented, some software that handles the output CSV file may malfunction if there is a BOM, so it is better to check the specifications of the software.

By the way, with the upcoming Windows 1019H1 update, it seems that notepad will be improved in many ways.
Many improvements to Notepad, no BOM UTF-8 to default save format ~"Windows 1019H1"


2022-09-30 21:39

First of all, why don't you check what byte values "Windows" and "Mac" have changed from what byte values on php?
After that, I think you can look into UTF-8.
I don't think I have enough knowledge.


2022-09-30 21:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.