0

I have detect my value to write is Thai language and I will write to CSV file but when I use fwrite and save .CSV file and open this CSV file in Excel.I see my text about "เธฅเธนเธเธเธฅเธดเนเธ,เธชเธฃเนเธฒเธเธฅเธฒเธข" Below this code

$xfile =fopen($filename,"w");
foreach( $data as $itm ){
     $outstr="";
     foreach($itm as $key=>$str){
            $val =str_replace("\r\n","",$str);
            val =str_replace("\t\t","",$val);
            $val =str_replace('"',"'",$val);
            $outstr=$outstr.'"'.$val.'"'.$clm;
            //dump(mb_detect_encoding($outstr));die(); --Result UTF-8
     }
$outstr=substr($outstr,0,strlen($outstr)-1);
fwrite($xfile,$outstr."\r\n"); //Newline
fclose($xfile);

I feel stupid Or i forgot something. Please help

patipat chewprecha
  • 255
  • 2
  • 6
  • 19
  • Use a library to write csv/excel file properly. https://github.com/PHPOffice – Mark Nov 17 '17 at 03:31
  • @Mark can you give me some example for symfony framework? – patipat chewprecha Nov 17 '17 at 03:40
  • you can browse sample directory. https://github.com/PHPOffice/PhpSpreadsheet/blob/develop/samples/Basic/16_Csv.php I'm not using symfony but installing phpspreadsheet with composer, using its namespace and calling it should work. try it in your controller first. Ived been using it for how many years. Its best for spreadsheets like csv. – Mark Nov 17 '17 at 03:45
  • 1
    @Mark Thanks a lot man. – patipat chewprecha Nov 17 '17 at 03:48
  • https://stackoverflow.com/questions/14809133/php-how-to-convert-array-into-csv-using-fputcsv-function/14809209#14809209 – Suhel Meman Nov 17 '17 at 03:59

2 Answers2

0

I use BOM with UTF-8 and insert after value. I see from this link

$xfile =fopen($filename,"w");
$BOM = "\xEF\xBB\xBF"; // UTF-8 BOM
fwrite($xfile, $BOM);
patipat chewprecha
  • 255
  • 2
  • 6
  • 19
0

Try mb_convert_encoding before you write.

$xfile =fopen($filename,"w");
foreach( $data as $itm ){
     $outstr="";
     foreach($itm as $key=>$str){
            $val =str_replace("\r\n","",$str);
            val =str_replace("\t\t","",$val);
            $val =str_replace('"',"'",$val);
            $outstr=$outstr.'"'.$val.'"'.$clm;
            //dump(mb_detect_encoding($outstr));die(); --Result UTF-8
     }
$outstr=substr($outstr,0,strlen($outstr)-1);
$outstr= mb_convert_encoding($outstr, "UTF-8");
fwrite($xfile,$outstr."\r\n"); //Newline
fclose($xfile);

Check detail here PHP_mb_convert_encoding

スージン
  • 143
  • 8