Problem with UTF-8 encoding and fwrite()

I’m trying to solve an issue with a client site, where all data is handled as UTF-8. The only problem is one section, where data is written to a .csv file for download - the diacritics/accents in the data are borked somewhere in the process.

Here’s my test case:

<?php
mb_internal_encoding('UTF-8');
header('Content-type: text/html; charset=UTF-8');

$myString = "Test with accents éèàç";
$fh=fopen('test.csv',"w");
fwrite($fh, utf8_encode($myString));
fclose($fh);
?>

This is taken directly from the php.net fwrite page, but it’s not doing me any good. :frowning:

Has anyone solved this problem before? :confused:

Which charset did you save the source file in?

I use Aptana, and the Text File Encoding is set to UTF-8.

If the source file is saved as UTF-8, then you shouldn’t use utf8_encode, since it’s a function for converting ISO-8859-1 -> UTF-8.

Ah, okay. But either way, it doesn’t result in the accented characters being stored in the .csv correctly. When I open the .csv file, the contents look like this:

Test with accents éèàç

or in a browser:

Test with accents éèà ç

(obviously mis-translated Latin 1).

The file is saved (correctly) as UTF-8, but if you open the file in a program and that program interprets the file as latin1, then it will look garbled. You need to make sure that the program is interpreting the file as UTF-8.