如何编写csv文件并在charset UTF-8

时间:2017-11-17 03:29:12

标签: php excel csv

我已经检测到我写的值是泰语,我会写入CSV文件,但是当我使用fwrite并保存.CSV文件并在Excel中打开此CSV文件时,我会看到我的文字&#34 ;เธฅเธนเธเธเธฅเธดเนเธ,เธชเธฃเนเธฒเธเธฅเธฒเธข"在此代码下面

$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);

我感到愚蠢或者我忘记了什么。请帮忙

2 个答案:

答案 0 :(得分:0)

我使用带有UTF-8的BOM并在值之后插入。我从link

中看到了
$xfile =fopen($filename,"w");
$BOM = "\xEF\xBB\xBF"; // UTF-8 BOM
fwrite($xfile, $BOM);

答案 1 :(得分:0)

在写之前尝试使用mb_convert_encoding。

$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);

在此查看详细信息PHP_mb_convert_encoding