php生成csv文件并提供下载及相关注意事项

1、生成文件过程略,只要逗号分割就可以了

2、提供下载加上如下代码:

header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header("Content-Length: ". filesize($file));
readfile($file);

3、如果数据是utf8的话,excel打开csv文件会乱码,解决方法:

1)、iconv/mb_convert_encoding 把utf8转换为gbk,此方法比较笨,不太好。

2)、加上bom 头,方法如下:

$head=pack('H*','EFBBBF');

$h=fopen($file,'w+');
fwrite($h,$content);

note:有同事说file_put_contents不能正确添加bom头,自己未验证过。

原文地址:https://www.cnblogs.com/argb/p/3144270.html