Home > php教程 > php手册 > body text

php 中文乱码 数据库存不上转记录

WBOY
Release: 2016-06-06 19:47:47
Original
928 people have browsed it

MySQL 存储php中json_encode格式中文问题及解决 MySQL存储php中json_encode格式信息,遇到中文时,会变成一堆类似uxxxx信息. 1.原因分析: 在存储到数据库时!MySQL不会存储unicode字符: MySQL仅支持从基本的多语种平面字符(00000-0xFFFF)。请尝试存储一个同义

 

MySQL 存储php中json_encode格式中文问题及解决

 

 

 

MySQL 存储php中json_encode格式信息  ,遇到中文时, 会变成一堆类似uxxxx信息.

 

 

 

1. 原因分析:
在存储到数据库时!MySQL 不会存储 unicode 字符:

 

MySQL 仅支持从基本的多语种平面字符 (0×0000-0xFFFF)。请尝试存储一个同义词相反:)

 

更新: MySQL 5.5.3 上 (其中尚未 GA), 支持补充字符如果您使用 UTF8MB4 编码。

 

json_encode中文的时候,会把每个中文字符encode成“\uxxxx”
而存进数据库的时候,“\”被屏蔽了,直接变成”uxxxx”

 

 

 

2. 解决问题:

 

知道是什么原因就好解决问题了,你可以选择其他存储方式;
或者再对症下药进一步转义”\”为“\\”,以保留”\”
我们的解决方案:

 

       1. 避免json_encode将中文转换unicode编码.
           PHP5.4版本,已经给Json新增了一个选项: JSON_UNESCAPED_UNICODE。加上这个选项后,就不会自动把中文编码了。

 

           $test= json_encode("深圳", JSON_UNESCAPED_UNICODE);

 

 

        2. 先将中文字段urlencode,json_encode后,再用urldecode,也可以保证中文不会被转成unicode。

 

            $test=urldecode(json_encode(array('brief'=>urlencode('简介'),'title'=>urlencode(标题)));

 

 

        3. 进一步转义”\”为“\\” 避免unicode中文前’\'被mysql当成特殊字符去除

 

             $str = json_encode('中文');

             $test= addslashes( $str ); 或 $test= mysql_escape_string( $str );

 

 

以上都可以直接插入mysql,问题解决

 

 

 

 

 

 

 

一.         首先是PHP网页的编码

1.     php文件本身的编码与网页的编码应匹配

a.     如果欲使用gb2312编码,那么php要输出头:header(“Content-Type: text/html; charset=gb2312"),静态页面添加

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!