PHP and UTF8 encoding issues - Tips and tricks to resolve
Typically, having the proper character encoding on a page can be a bit of a pain, even if you have the right meta-tag. Here are some tips on how to ease the issue.
- Add the following to the top of your php page:
ini_set('default_charset', 'UTF-8'); header('content-type: text/html; charset: utf-8'); mb_language('uni'); mb_internal_encoding('UTF-8');
- Be sure that your databases in tables in mysql have a utf-8 correlation. This can be changed in phpMyAdmin under the options tab.
- Make sure your MySQL query declares UTF-8
//currently: PDO $conn_info = 'mysql:host=localhost; dbname=test; charset=UTF8'; $dbh = new PDO($conn_info, $db_user, $db_password); //Before 5.3.6: PDO $db = new PDO($con, $db_user, $db_password); $db->exec('set names utf8'); //not recommended! if ($db = @mysql_connect($host, $username, $password)) { mysql_select_db($databasename, $db); mysql_set_charset("utf8"); mysql_query('SET NAMES utf8'); //code here }
- Make sure the php file is in UTF-8, not ASCII: Text editors such as sublime, can convert the page to UTF-8 for you, as post editors (and IDE's) may actually use ASCII. To convert the file to UTF-8 in sublime Text, go to file > Save with encoding > UTF-8. Its recommended that PDO databases access is used. Check out this Tuts+ Article: Why You Should Be Using PHP's PDO for Database Access for more information
- Be sure yor web view uses the UTF meta encoding tag as well:
<meta charset="UTF-8">
- Lastly, be sure to check your code editor's settings to make sure you are viewing it in UTF-8 encoding.