PHP Streaming CSV always adds UTF-8 BOM

别来无恙 提交于 2019-12-20 03:23:39

问题


The following code gets a 'report line' as an array and uses fputcsv to tranform it into CSV. Everything is working great except for the fact that regardless of the charset I use, it is putting a UTF-8 bom at the beginning of the file. This is exceptionally annoying because A) I am specifying iso and B) We have lots of users using tools that show the UTF-8 bom as characters of garbage.

I have even tried writing the results to a string, stripping the UTF-8 BOM and then echo'ing it out and still get it. Is it possible that the issue resides with Apache? If I change the fopen to a local file it writes it just fine without the UTF-8 BOM.

header("Content-type: text/csv; charset=iso-8859-1");
header("Cache-Control: no-store, no-cache");
header("Content-Disposition: attachment; filename=\"report.csv\"");

$outstream = fopen("php://output",'w');

for($i = 0; $i < $report->rowCount; $i++) {
    fputcsv($outstream, $report->getTaxMatrixLineValues($i), ',', '"');
}
fclose($outstream);

exit;

回答1:


My guess would be that your php source code file has a BOM, and you have php's output buffering enabled.




回答2:


I don't know if this solves your problem but have you tried using the print and implode functions to do the same thing?

header("Content-type: text/csv; charset=iso-8859-1");
header("Cache-Control: no-store, no-cache");
header("Content-Disposition: attachment; filename=\"report.csv\"");

for($i = 0; $i < $report->rowCount; $i++) {
    print(implode(',',$report->getTaxMatrixLineValues($i)));
}

That's not tested but pretty obvious.



来源:https://stackoverflow.com/questions/2576520/php-streaming-csv-always-adds-utf-8-bom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!