UTF-8 characters don't display correctly

て烟熏妆下的殇ゞ 提交于 2019-11-28 12:07:14

What's the encoding of your file? It should be UTF8 too. What's the default charset of your http server? It should be UTF-8 as well.

Encoding only works if:

  • the file is encoded correctly
  • the server tells what's the encoding of the delivered file.

When working with databases, you also have to set the right encoding for your DB fields and the way the MySQL client communicates with the server (see mysql_set_charset()). Fields only are not enough because your MySQL client (in this case, PHP) could be set to ISO by default and reinterprets the data. So you end up with UTF8 DB -> ISO client -> injected into UTF8 PHP script. No wonder why it's messed up at the end :-)

How to serve the file with the right charset?

header('Content-type: text/html; charset=utf-8') is one solution

.htaccess file containing AddDefaultCharset UTF-8 is another one

HTML meta content-type might work too but it's always better to send this information using HTTP headers.

PS: you also have to use mb_strlen() because strlen() on UTF8 strings will probably report more than the real length.

I suppose, your code is in windiws-1251 since it is Russian :) convert your string to utf-8:

$str = iconv('windows-1251', 'utf-8', $str);

If you're going to send a mix of data and don't want to specify utf-8 using a php header, you can add this html to your page:

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

If your database is UTF-8, it's ok for mysql.

For your echo, if you do it in a web site, put this in the top page:

header('Content-Type: text/html; charset=UTF-8');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!