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:

Create a GIF animation image for free

I need to create a banner ad for Stork’s advanced feature (NIH grant database English/Chinese bilingual version). I wish the ad has two images...
Xu Cui
19 sec read

Leave a Reply

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