Horrible combination, spent all day on this!
My goal was to take some data (which contain UTF-8 unicode characters), generate a CSV file using PHP and send it via mail. The problem is that Microsoft Excel doesn`t accept UTF-8 CSV files.
Some people suggest using mb_convert_encoding($contents, "ISO-8859-1", "UTF-8"); or mb_convert_encoding($contents, "UTF-16LE", "UTF-8");, neither worked for me, though I have multibyte extension installed
It seems that the solution is different by server setups. This solution worked for me:

$message= iconv("UTF-8","WINDOWS-1257",html_entity_decode( $message ,ENT_COMPAT,'utf-8'));

You might want to change “WINDOWS-1257” to something else, like WINDOWS-1255 or WINDOWS-1252 or ISO-8859-1, etc.. My server did not have the “iconv” function enabled, so I asked server administrator to enable it and it worked!

9 Responses to “PHP, UTF-8 encoding, CSV and Excel”

  1. molikas

    thank you really helped=]

    November 8th, 2009 | 10:49
  2. Kai

    works like a charm! thanks for sharing!

    December 3rd, 2009 | 04:34
  3. Ben

    Yeah! Thanks a lot for this hint man! This tip made my day.

    December 3rd, 2009 | 04:38
  4. Raduzz

    i have been looking for sotution for 3 hours.
    finally i have found yours.

    thx a lot

    December 26th, 2009 | 12:48
  5. artis

    header(‘Content-Description: File Transfer’);
    header(‘Content-Type: application/vnd.ms-excel’);
    header(‘Content-Disposition: attachment; filename=report-’.date(‘Y-m-d’)’.csv’);
    header(‘Content-Transfer-Encoding: binary’);
    header(‘Expires: 0′);
    header(‘Cache-Control: must-revalidate, post-check=0, pre-check=0′);
    header(‘Pragma: public’);
    header(‘Content-Length: ‘. strlen($csv));
    echo chr(255) . chr(254) . mb_convert_encoding($csv, ‘UTF-16LE’, ‘UTF-8′);

    only this works for me

    December 8th, 2010 | 11:10
  6. Chavdar

    thank you! Work!

    February 19th, 2011 | 12:17
  7. This iconv code works!!!
    You are my savior.Thnx

    February 27th, 2011 | 12:30
  8. Pero

    THANK YOU!!! For Croatian language i just had to change “WINDOWS-1257″ to “WINDOWS-1250″!

    August 27th, 2011 | 06:07
  9. starex

    you are my hero

    November 17th, 2011 | 04:59

Leave a Reply

Bad Behavior has blocked 629 access attempts in the last 7 days.