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');

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

Record screen and convert to GIF

Stork has an update and we need to send an email to our users. In the email we wish to show a super short...
Xu Cui
43 sec read

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

Leave a Reply

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