59

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));
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Yuseferi
  • 7,931
  • 11
  • 67
  • 103

4 Answers4

200

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.

Hardy
  • 5,590
  • 2
  • 18
  • 27
36

Try this also:

$df = fopen($filepath, 'w');
$array = array($coupon->code, $discount->label);
$array = array_map("utf8_decode", $array);
fputcsv($df, $array);
robsonsanches
  • 1,267
  • 11
  • 9
5

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.

Syno
  • 1,056
  • 10
  • 25
0

Similar to others, but works for me

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

before fputcsv your data