Some Tricks to Sort Out the utf-8 Problem


Everyone already knows about utf-8 problem, but sometimes the issue still persists even after approaches so many solutions. So in this tutorial I am including some tricks that will surly help you to sort out the utf-8 problem. Like the problem with currency symbols(£, ₹), the solution is based on HTML, PHP and MySQL tricks.

In PHP you should use following line:

<?php header("Content-type: text/html; charset=utf-8"); ?>

You can set content type using following meta tag line also:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Also, you should note that the

element has an ‘accept-charset’ attribute which should also be set to utf-8 like below:

<form accept-charset="utf-8" method="POST" ...> ...  </form>

In MySQL you should use following tricks to resolve the utf-8 problems:

Make sure your database table’s collation is utf8_general_ci and that all string fields within the table also have the utf8_general_ci collation.

Now the really important points: make sure your client connection is also using UTF-8:

For mysql:

mysql_set_charset('utf8');

or for mysqli:

mysqli_set_charset('utf8');

or execute the SQL immediately after connection:

SET NAMES UTF8;

or for PDO:

$handle = new PDO("mysql:host=localhost;dbname=dbname",
    'username', 'password',
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

I hope this tutorial will help you to sort out the utf-8 problem.