解决PHP导出CSV文中文乱码问题
csv文件可以使用excel打开并进行一些操作了,同时我们用php导入csv文件是非常的简单了,所以我们通常会使用php来导出csv了,但有时会碰到在使用Excel打开csv时出现乱码问题了,下面我们就来看解决办法。
乱码情况
写了一段导出 CSV 文件的代码,可以正常输出
使用 CSV 和 TXT 程序打开文件是正常的,但是使用 Excel 打开文件就出现了中文乱码的问题(这就奇怪了, 为什么在 Excel 中会乱码呢?)
通过查看编码发现,导出的 CSV 文件是 UTF-8 无BOM编码格式,而我们通常使用 UTF-8 编码格式 都是有 BOM 的。
尝试着添加了 BOM 之后,中文乱码的问题有解决了。
添加 BOM 到 CSV 文件中
示例代码:
$file = fopen($export_file_path, 'w');
fwrite($file, chr(0xEF).chr(0xBB).chr(0xBF)); // 添加 BOM
foreach ($contens as $content) {
fputcsv($file, $content);
}
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);//转换编码
if(fwrite($handle,$strUsersData)==false){}
fclose($handle);
down_file($fname,'555.csv');

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools