$my_data = [ [1, 2, 3, 4, 5, 7], [9, 8, 7, 6, 5, '中文'], ]; header("Content-Type: text/csv"); header("Content-Disposition: attach;filename=filename.csv"); $h = fopen("php://output", "w"); fwrite($h, chr(0xEF).chr(0xBB).chr(0xBF)); // 添加 BOM foreach($my_data as $data) { fputcsv($h, $data); } fclose($h);
分析:使用 CSV 和 TXT 程序打开文件是正常的,但Excel打开中文乱码,通过查看编码发现,导出的 CSV 文件是 UTF-8 无BOM编码格式。
$f = fopen("contacts.csv", "r"); while($line = fgetcsv($f, 1000, ",")) { echo "Contact: {$line[1]}"; }
//导入CSV表格:CSV转数组 $fp = fopen('file.csv','r'); while ( ($row = fgetcsv($fp)) !== FALSE ) { //从文件指针中读入一行并解析CSV $arr[] = $row; } fclose($fp); var_export($arr);