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:

<?php
header("Content-Type: application/vnd.ms-excel; charset=UTF-16LE");
header("Content-Disposition: attachment; filename=\"Export Excel\"");
mysql_connect("localhost","root","");
mysql_select_db("fake");
$sql = "SELECT * FROM users ORDER BY user_name";
$req = mysql_query($sql);
?>
<html><head></head><body>
  <table>
    <tr>
      <td>Name</td>
      <td>Firstname</td>
      <td>Email</td>
    </tr>
<?
while ($row = @mysql_fetch_assoc($req))
{
?>
    <tr>
      <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>
    </tr>
<?
}
?>
  </table>
</body></html>
Tags:  charsetmicrosoftmysqlphp.
Posted the Tuesday 28 april 2009 18:23:05