I have a PHP application which generates a simple CSV file using league/csv. Some of the columns contains names/addresses which might have non-ANSI values. My client is requiring that the output CSV file be encoded in iso-8859-1
instead of utf-8
as it is currently.
I believe my problem can be reduced to the following (where response
is from laravel):
$headers = [
'Content-type' => "text/csv; charset=iso-8859-1",
'Content-Disposition' => 'attachment; filename="CLI.csv"'
];
return response()->stream(function() {
$fh = fopen('php://output', 'wb');
fwrite($fh, "Vià Cittè\n");
fwrite($fh, mb_convert_encoding("Vià Cittè\n", 'iso-8859-1'));
fwrite($fh, mb_convert_encoding("Vià Cittè\n", 'iso-8859-1', 'utf-8'));
fwrite($fh, iconv('utf-8', 'iso-8859-1', "Vià Cittè\n"));
fwrite($fh, utf8_decode("Vià Cittè\n"));
fwrite($fh, utf8_encode("Vià Cittè\n"));
fclose($fh);
}, 200, $headers);
I would expect at least some of the lines to be Vià Cittè\n
encoded in iso-8859-1 but they all end up wrong. This is what I see when I open the output file using iso-8859-1 as encoding:
It appears that the output gets reencoded as utf-8 for some reason.
Can someone tell me how I can avoid having this reencoding issue?
In my real code I'm not writing directly using fopen
, I use league/csv with its Writer
and CharsetConverter
. I have made various attempts but the result is the same as described above.
Note: I'm currently using PHP 7.3 on linux. The php server is inside a docker container behind an nginx proxy (which is in a different docker container).