Search code examples
phpmysqlencodingutf-8string-conversion

What is the best way to convert a string to UTF-8 in PHP?


I am wondering what the best way to convert an string into UTF-8 using PHP is.

The following looks ok on the page, but in MySQL some characters are looking garbled.

  • MYSQL: UPGRADE EVENT – New Mazda2 from £124.99 per month. Representative 0% APR over 3 years. Min 50% deposit required. Call xxxxxxxxxxxx for test drive, info or Ts&Cs.
  • ON PAGE: UPGRADE EVENT - New Mazda2 from £124.99 per month. Representative 0% APR over 3 years. Min 50% deposit required. Call xxxxxxxxxxxx for test drive, info or Ts&Cs.

I have looked at iconv, mb_string, html_entity_decode, htmlentities, mb_convert_encoding etc..

The database collation is utf8_unicode_ci and the tables' charset is utf8.


Solution

  • Try using mysql_query("SET NAMES 'utf8'") (or dbh->exec("SET NAMES 'utf8'")) to set the encoding of the connection.