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

5
  • Use a library to write csv/excel file properly. github.com/PHPOffice Commented Nov 17, 2017 at 3:31
  • @Mark can you give me some example for symfony framework? Commented Nov 17, 2017 at 3:40
  • you can browse sample directory. github.com/PHPOffice/PhpSpreadsheet/blob/develop/samples/Basic/… 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. Commented Nov 17, 2017 at 3:45
  • 1
    @Mark Thanks a lot man. Commented Nov 17, 2017 at 3:48
  • stackoverflow.com/questions/14809133/… Commented Nov 17, 2017 at 3:59

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.