Software is like sex... It's better when it's free.

Blog - UTF-8 encoding with Excel

UTF-8 encoding with Excel

If you have tried repeatedly to produce an excel export of data from a database in UTF-8 with PHP, you probably came to some surprising results.

Our dear friend Microsoft uses in fact the encoding UTF-16le.

Thus, to form a excel document (here a list of users), "simply" do:

header("Content-Type: application/; charset=UTF-16LE");
header("Content-Disposition: attachment; filename=\"Export Excel\"");
$sql = "SELECT * FROM users ORDER BY user_name";
$req = mysql_query($sql);
while ($row = @mysql_fetch_assoc($req))
      <td><?=substr(chr(255).chr(254).mb_convert_encoding($row['user_sname'], "UTF-16LE", "UTF-8"),2)?></td>
      <td><?=substr(chr(255).chr(254).mb_convert_encoding($row['user_fname'], "UTF-16LE", "UTF-8"),2)?></td>
      <td><?=substr(chr(255).chr(254).mb_convert_encoding($row['user_email'], "UTF-16LE", "UTF-8"),2)?></td>
Tags:  charsetmicrosoftmysqlphp.
Posted the Tuesday 28 april 2009 18:23:05