write utf-8 characters to file with fputcsv in php
61,417
Solution 1
Try this:
$df = fopen($filepath, 'w');
fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
fputcsv($df, array($coupon->code, $discount->label));
the line fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
writes file header for correct encoding.
Solution 2
Try this also:
$df = fopen($filepath, 'w');
$array = array($coupon->code, $discount->label);
$array = array_map("utf8_decode", $array);
fputcsv($df, $array);
Solution 3
If you want make a UTF-8 file for excel, use this simple solution:
$fp = fopen($filename, 'w');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
See the original answer here on the official PHP page.
Comments
-
Yuseferi almost 2 years
I want to try write Persian character in CSV file in PHP, I am using
fputcsv
function but how can write UTF-8 character to CSV file withfputcsv
?Part of my code:
$df = fopen($filepath, 'w'); fputcsv($df, array($coupon->code, $discount->label));
-
mwfearnley almost 8 yearsWhat does this answer do?
-
Solrac over 7 yearsThis will decode your UTF8 strings into single byte ISO-8859-1. This NOT what the OP was asking for.
-
Faris Rayhan over 6 yearsYou also have to take consideration in excel perspective. Make sure the excel already encoded in UTF-8
-
Phuong over 6 yearsGood solution. Thanks Hardy!
-
Chinmay235 about 6 years@FarisRayhan Same things here.. :(
-
Ahmad Baktash Hayeri about 5 yearsCould you please explain what the three characters are and what is their purpose in fixing the UTF8 problem?
-
Herbert Van-Vliet over 4 years@AhmadBaktashHayeri those bytes make up the Byte Order mark (BOM) for UTF-8
-
Ali over 3 yearsMy hero, saved my day :-*
-
Ross over 3 yearsThis is clearer in my opinion and leaves the work to be done by utf8_decode and not requiring the reader to obey the BOM.
-
rutex about 2 yearsThis works great but in my case it makes some fields not to be printed to the excel file. Any idea why is that?