csv文件可以使用excel打開并進(jìn)行一些操作了,同時(shí)我們用php導(dǎo)入csv文件是非常的簡(jiǎn)單了,所以我們通常會(huì)使用php來(lái)導(dǎo)出csv了,但有時(shí)會(huì)碰到在使用Excel打開csv時(shí)出現(xiàn)亂碼問(wèn)題了,下面我們就來(lái)看解決辦法.
亂碼情況
寫了一段導(dǎo)出 CSV 文件的代碼,可以正常輸出,使用 CSV 和 TXT 程序打開文件是正常的,但是使用 Excel 打開文件就出現(xiàn)了中文亂碼的問(wèn)題(這就奇怪了,為什么在 Excel 中會(huì)亂碼呢?)
通過(guò)查看編碼發(fā)現(xiàn),導(dǎo)出的 CSV 文件是 UTF-8 無(wú)BOM編碼格式,而我們通常使用 UTF-8 編碼格式 都是有 BOM 的.
嘗試著添加了 BOM 之后,中文亂碼的問(wèn)題有解決了。愛掏網(wǎng) - it200.com
添加 BOM 到 CSV 文件中
示例代碼:
$file?=?fopen($export_file_path,?'w');?
fwrite($file,?chr(0xEF).chr(0xBB).chr(0xBF));?//?添加?BOM?
foreach?($contens?as?$content)?{?
????????fputcsv($file,?$content);?
}?//phpfensi.com?
fclose($file);?
另一種解決辦法:
function?down_file($filepath,$filename)?
{?
if(!file_exists($filepath))?
{?
echo?"backup?error?,download?file?no?exist";?
exit();?
}?
ob_end_clean();?
header('Content-Type:?application/download');?
header("Content-type:?text/csv");?
header('Content-Disposition:?attachment;filename="'.$filename.'"');?
header("Content-Encoding:?binary");?
??header("Content-Length:".filesize($filepath));?
header("Pragma:?no-cache");?
header("Expires:?0");?
readfile($filepath);?
$e=ob_get_contents();?
ob_end_clean();?
}?
?
$fname='usersdata.csv';?
$handle=fopen($fname,'wb');?
$strUsersData?=iconv('utf-8','gb2312',$strUsersData);//轉(zhuǎn)換編碼?
if(fwrite($handle,$strUsersData)==false){}?
fclose($handle);?
down_file($fname,'555.csv');?