Create CSV file containing UTF-8 characters in PHP and Javascript

23 sec read

If you create a CSV file and the file contains some characters such as ü or ş, then you will find the characters are not displayed correctly in Excel. This is because the default coding of Excel is not UTF-8. To force Excel to use UTF-8, we need to add BOM (Byte Order Mark) in the beginning of the file.

// PHP
$fp = fopen($myFile, 'w');
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
fputcsv($fp, $otherdata);
// Javascript
var csvFormattedDataTable = '';
csvFormattedDataTable += "\uFEFF";
csvFormattedDataTable += "other stuff";
var encodedUri = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvFormattedDataTable);
$(buttonName).attr("href", encodedUri);
$(buttonName).attr("download", 'table-data.csv');
$(buttonName).attr("target", '_blank');

Don't want to miss new papers in your field? Check out Stork we developed:

Google Password Checkup, find which password is compromised

It’s not uncommon you hear news about data breaches of some big internet companies. If you happen to you use their services, your username/password...
Xu Cui
22 sec read

Oracle VirtualBox, Failed to open a session

I like to play with computers. So Oracle’s VirtualBox is handy to install different operating systems (Linux, Windows, Mac etc) and try them. But...
Xu Cui
30 sec read

FileMarker, colorize a file on Windows 10

In Mac, you can colorize a folder or file. This is particular useful if you have many files and want to mark important ones...
Xu Cui
22 sec read

Leave a Reply

Your email address will not be published. Required fields are marked *