专业编程基础技术教程

网站首页 > 基础教程 正文

php导出csv乱码的解决办法

ccvgpt 2024-11-23 11:53:05 基础教程 1 ℃
//BOM
$bom =chr(0xEF).chr(0xBB).chr(0xBF); 
//在写入的第一个字符串开头加 bom。
function transCode(array &$arr){
    foreach ($arr as &$v) {
        $v = "\t".iconv('utf-8', 'gb2312//ignore', $v);
    }
    }    

//组织数据
$headset = [
     '序号','条码','仓库','客户编码','客户','数量','扫码人员','扫码时间'
];
//以下数组数据,为数据库查询得到的。具体根据自己需求组织
//$excel_body_row[] 列数据
$excel_body=array();
          foreach ($rss as $rs){
            $excel_body_row=array();
            $excel_body_row[]="\t".iconv('utf-8', 'gb2312//ignore', $rs->Id);
            $excel_body_row[]="\t".iconv('utf-8', 'gb2312//ignore', $rs->codenum);
            $excel_body_row[]="\t".iconv('utf-8', 'gb2312//ignore', $rs->Sname);
            $excel_body_row[]="\t".iconv('utf-8', 'gb2312//ignore', $rs->Ccode);
            $excel_body_row[]="\t".iconv('utf-8', 'gb2312//ignore', $rs->Cname);
            $excel_body_row[]="\t".iconv('utf-8', 'gb2312//ignore', $rs->pnum);
            $excel_body_row[]="\t".iconv('utf-8', 'gb2312//ignore', $rs->realname);
            $excel_body_row[]="\t".iconv('utf-8', 'gb2312//ignore',date("Y-m-d H:i:s",$rs->scandate));
            $excel_body[]=$excel_body_row;
          }

$headset_code=transCode($headset);
    $fileName = date('YmdHis');
//浏览器下载
    header('pragma:public');
    header('Content-Type: application/csv;charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $fileName . '.csv"');
    $file = fopen('php://output', 'w') or die("Can't open php://output");

     fputcsv($file,$headset);
    foreach ($excel_body as $line){
        fputcsv($file, $line);
    }
   fclose($file);

Tags:

最近发表
标签列表