Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write utf-8 characters to file with fputcsv in php

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));
like image 953
Yuseferi Avatar asked Feb 24 '14 13:02

Yuseferi


3 Answers

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.

like image 161
Hardy Avatar answered Nov 15 '22 06:11

Hardy


Try this also:

$df = fopen($filepath, 'w');
$array = array($coupon->code, $discount->label);
$array = array_map("utf8_decode", $array);
fputcsv($df, $array);
like image 33
robsonsanches Avatar answered Nov 15 '22 06:11

robsonsanches


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.

like image 4
Syno Avatar answered Nov 15 '22 06:11

Syno