php json数据中文乱码问题怎么办

后端开发   发布日期:2023年06月07日   浏览次数:535

php json数据中文乱码问题的解决办法:1、打开相应的php文件;2、在“json_encode()”方法中添加一个参数“JSON_UNESCAPED_UNICODE”即可正常输出中文。

本教程操作环境:Windows10系统、PHP8.1版、DELL G3电脑

php json数据中文乱码问题怎么办?

解决php转json后的中文乱码

问题:

在php中读取数据库的数据,可以用var_dump / print_r 正确读出中文数据,但是转了json格式后,中文数据就变成乱码了类似于 "\u5c0f\u660e";

解决方法:

在json_encode()方法中添加多一个参数JSON_UNESCAPED_UNICODE;

例如:json_encode($this->cjarr,JSON_UNESCAPED_UNICODE);

为什么要加JSON_UNESCAPED_UNICODE,查询后我的理解:

php中的json_encode在处理中文数据时会进行编码,得到类似于 "\u5c0f\u660e" 的字符串,使得读取数据不便,添加JSON_UNESCAPED_UNICODE后就不用编译中文码 Unicode,正常输出中文

问题代码:

  1. //读取所有数据
  2. public function SelectAll(){
  3. $sql = 'SELECT * FROM `websql`';
  4. mysqli_query($this->link,'set names utf8');
  5. $results = mysqli_query($this->link, $sql);
  6. while($row = mysqli_fetch_assoc($results)){
  7. array_push($this->cjarr,$row);
  8. }
  9. }
  10. public function a(){
  11. print_r($this->cjarr);//未转json格式前
  12. echo '<br><br>';
  13. echo json_encode($this->cjarr);//转json格式后
  14. }

解决问题代码:

  1. //读取所有数据
  2. public function SelectAll(){
  3. $sql = 'SELECT * FROM `websql`';
  4. mysqli_query($this->link,'set names utf8');
  5. $results = mysqli_query($this->link, $sql);
  6. while($row = mysqli_fetch_assoc($results)){
  7. array_push($this->cjarr,$row);
  8. }
  9. //添加JSON_UNESCAPED_UNICODE 后解决该问题
  10. $this->jsonCjarr = json_encode($this->cjarr,JSON_UNESCAPED_UNICODE);
  11. }
  12. public function a(){
  13. print_r($this->cjarr);//未转json格式前
  14. echo '<br><br>';
  15. echo $this->jsonCjarr; //输出
  16. }

以上就是php json数据中文乱码问题怎么办的详细内容,更多关于php json数据中文乱码问题怎么办的资料请关注九品源码其它相关文章!