Home > Article > Backend Development > PHP output CSV file garbled problem_PHP tutorial
Problem: The PHP input user list is a csv file. When opened with excel, it is displayed as garbled characters. When opened with notepad or ue, it is normal. When viewing the file encoding, it is displayed as utf-8
Solution:
function down_file($filepath,$filename)
{
if(!file_exists($filepath))
{ www.2cto.com
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);//Convert encoding
if(fwrite($handle,$strUsersData)==false){}
fclose($handle);
down_file($fname,'555.csv');