54

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 with fputcsv?

Part of my code:

$df = fopen($filepath, 'w');
fputcsv($df, array($coupon->code, $discount->label));

4 Answers 4

192

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.

5
  • 1
    You also have to take consideration in excel perspective. Make sure the excel already encoded in UTF-8 Nov 2, 2017 at 7:50
  • 3
    Could you please explain what the three characters are and what is their purpose in fixing the UTF8 problem? Feb 5, 2019 at 4:13
  • 1
    @AhmadBaktashHayeri those bytes make up the Byte Order mark (BOM) for UTF-8 Sep 8, 2019 at 7:11
  • This works great but in my case it makes some fields not to be printed to the excel file. Any idea why is that?
    – rutex
    Mar 12, 2022 at 7:48
  • See also answer to stackoverflow.com/questions/40447325/… - if this doesn't work need to echo the characters before as well
    – softfrog
    Sep 12, 2022 at 8:20
34

Try this also:

$df = fopen($filepath, 'w');
$array = array($coupon->code, $discount->label);
$array = array_map("utf8_decode", $array);
fputcsv($df, $array);
4
  • 1
    What does this answer do?
    – mwfearnley
    Jul 1, 2016 at 12:08
  • 2
    This will decode your UTF8 strings into single byte ISO-8859-1. This NOT what the OP was asking for.
    – Solrac
    Sep 1, 2016 at 17:11
  • @FarisRayhan Same things here.. :(
    – Chinmay235
    Apr 26, 2018 at 6:53
  • This is clearer in my opinion and leaves the work to be done by utf8_decode and not requiring the reader to obey the BOM.
    – Ross
    Dec 1, 2020 at 13:14
4

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.

0

Similar to others, but works for me

fputs($output_file, chr(0xEF) . chr(0xBB) . chr(0xBF) );

before fputcsv your data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.