UTF-8字符无法正确显示 [英] UTF-8 characters don't display correctly

查看:233
本文介绍了UTF-8字符无法正确显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的PHP代码:

<?php
$result = '';
$str = 'Тугайный соловей';
for ($y=0; $y < strlen($str); $y++) {
    $tmp = mb_substr($str, $y, 1);
    $result = $result . $tmp;
}
echo 'result = ' . $result;

输出为:

Тугайный Ñоловей

我该怎么办?我必须将$result放入MySQL数据库.

What can I do? I have to put $result into a MySQL database.

推荐答案

文件的编码是什么?它也应该是UTF8.您的http服务器的默认字符集是什么?它也应该是UTF-8.

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:

  • 文件编码正确
  • 服务器告诉所传送文件的编码是什么.

使用数据库时,还必须为数据库字段 和MySQL客户端与服务器通信的方式设置正确的编码(请参见mysql_set_charset()).仅字段是不够的,因为默认情况下您的MySQL客户端(在本例中为PHP)可以设置为ISO并重新解释数据.因此,最终将UTF8 DB-> ISO客户端->注入到UTF8 PHP脚本中.难怪为什么最后搞砸了:-)

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')是一种解决方案

.htaccess文件是另一个

.htaccess file containing AddDefaultCharset UTF-8 is another one

HTML元内容类型也可能起作用,但是使用HTTP标头发送此信息总是更好.

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

PS:您还必须使用mb_strlen(),因为UTF8字符串上的strlen()可能报告的比实际长度还多.

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

这篇关于UTF-8字符无法正确显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆