【问题标题】:How to write csv file and open in MS.Excel in charset UTF-8如何以字符集 UTF-8 编写 csv 文件并在 MS.Excel 中打开
【发布时间】:2018-04-30 18:25:34
【问题描述】:

我检测到我要写入的值是泰语,我将写入 CSV 文件,但是当我使用 fwrite 并保存 .CSV 文件并在 Excel 中打开此 CSV 文件时。我看到了关于“เธฅเธน”的文本เธเธเธฅเธดเนเธ,เธชเธฃเนเธฒเธเธฅเธฒเธข”下面的代码

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

我觉得自己很愚蠢,或者我忘记了什么。请帮忙

【问题讨论】:

标签: php excel csv


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在编写之前尝试 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

    【讨论】:

      猜你喜欢
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 2014-03-21
      • 2013-12-29
      相关资源
      最近更新 更多