新建表Clubs CREATE TABLE `Clubs` ( `id` int ( 11 ) NOT NULL AUTO_INCREMENT, `name` varchar ( 30 ) CHARACTER SET utf8 NOT NULL DEFAULT '' , PRIMARY KEY (`id`)) ENGINE = MyISAM AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8 COLLATE = utf8_unicode
新建表Clubs
<span>CREATE</span> <span>TABLE</span><span> `Clubs` ( `id` </span><span>int</span>(<span>11</span>) <span>NOT</span> <span>NULL</span><span> AUTO_INCREMENT, `name` </span><span>varchar</span>(<span>30</span>) <span>CHARACTER</span> <span>SET</span> utf8 <span>NOT</span> <span>NULL</span> <span>DEFAULT</span> <span>''</span><span>, </span><span>PRIMARY</span> <span>KEY</span><span> (`id`) ) ENGINE</span><span>=</span>MyISAM AUTO_INCREMENT<span>=</span><span>1</span> <span>DEFAULT</span> CHARSET<span>=</span>utf8 COLLATE<span>=</span>utf8_unicode_ci;
id name
1 程序员
2 架构师
3 产品经理
4 测试
如果在phpMyAdmin中查看name字段内容就是?,修改MySQL 字符集选择UTF8,MySQL 连接校对选择utf8_general_ci
在mysql中查看字段内容为正确的中文字符后,通过mysql_query('select * from clubs')查询
用var_dump打印查询结果如下,所有的中文汉字都变成了?
<span>array</span> (size=4<span>) </span>0 => <span>array</span> (size=2<span>) </span>'id' => <span>string</span> '1' (length=1<span>) </span>'name' => <span>string</span> '???' (length=3<span>) </span>1 => <span>array</span> (size=2<span>) </span>'id' => <span>string</span> '2' (length=1<span>) </span>'name' => <span>string</span> '???' (length=3<span>) </span>2 => <span>array</span> (size=2<span>) </span>'id' => <span>string</span> '3' (length=1<span>) </span>'name' => <span>string</span> '????' (length=4<span>) </span>3 => <span>array</span> (size=2<span>) </span>'id' => <span>string</span> '4' (length=1<span>) </span>'name' => <span>string</span> '??' (length=2)
解决办法:在执行mysql_query之前先执行
<span>mysql_query</span>("set names utf8");
如果还不行,请确认php文件编码格式是否是utf8格式,同时在php文件头增加
<span>header</span>("Content-Type:text/html;charset=utf-8");
解决问题的根本办法就是把相关的编码格式都统一为utf8。
查询结果中文字符没问题了,但是$clubs转化为json时,name字段中文字符却又变了
<span>$clubs</span>=json_encode(<span>$clubs</span><span>); </span><span>echo</span>(<span>$clubs</span>);
输出内容如下
[{"id":"1","name":"\u7a0b\u5e8f\u5458"},{"id":"2","name":"\u67b6\u6784\u5e08"},{"id":"3","name":"\u4ea7\u54c1\u7ecf\u7406"},{"id":"4","name":"\u6d4b\u8bd5"}]
解决方案:
<span>foreach</span> ( <span>$clubs</span> <span>as</span> <span>$key</span> => <span>$value</span><span> ) { </span><span>foreach</span>(<span>$value</span> <span>as</span> <span>$k</span>=><span>$v</span><span>){ </span><span>$clubs</span>[<span>$key</span>][<span>$k</span>] = <span>urlencode</span>(<span>$v</span><span>); } } </span><span>$clubs</span>=json_encode(<span>$clubs</span><span>); </span><span>echo</span>(<span>urldecode</span>(<span>$clubs</span>));
原因:
json_encode只支持UTF8编码的字符,使用JSON作为提交和接收的数据格式时,字符都采用UTF8编码处理,当我们的页面编码和数据库编码不是采用UTF8的时候,就极容易出现中文乱码的问题。解决办法是在用js或者PHP处理JSON数据的时候都采用UTF8的形式。