Home  >  Article  >  Backend Development  >  为啥PHP 处理数据库 读出"张三"的编码而不是 汉字

为啥PHP 处理数据库 读出"张三"的编码而不是 汉字

WBOY
WBOYOriginal
2016-06-13 12:00:29807browse

为什么PHP 处理数据库 读出"张三"的编码而不是 汉字?

本帖最后由 gunzi318 于 2014-06-17 19:14:13 编辑
    $con = mysql_connect("localhost","root","1234");  
    mysql_select_db("test",$con);  

mysql_query("set names utf8"); 
mysql_query("set character_set_client=utf8"); 
    mysql_query("set character_set_results=utf8");


    $q=mysql_query("SELECT * FROM people");  
    while($e=mysql_fetch_assoc($q)){
        $output[]=$e;  }
        print(json_encode($output));  
        mysql_close();  
?>  



输出结果:
[{"id":"10","name":"John","sex":"1","birthyear":"1979"},{"id":"11","name:"\u5f20\u4e09","sex":"1","birthyear":"1989"}]

为什么不是 张三
------解决方案--------------------
因為你json_encode了,中文會轉未union編碼

print(json_encode($output)); 
改成
print($output); 

如果你json_encode后也想看到中文,可以參考我之前寫的文章:http://blog.csdn.net/fdipzone/article/details/28766357
------解决方案--------------------
json_encode 只接受 utf-8 编码的数据
json_encode 在做 json 编码时,会将多字节的 utf-8 字符转换成双字节的 unicode 编码的实体形式
这样在任何环境中bouquet不会因编码的原因造成数据的失真
json 数据格式主要用于与 js 通讯,而浏览器会将任何编码的数据转换成其工作字符集 unicode
所以,json_encode 的转码工作有利于减轻浏览器的压力
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn