Problem with json_encode Chinese encoding in php

怪我咯
Release: 2023-03-13 19:44:01
Original
1844 people have browsed it

In actual application, when there are Chinese characters, when using json_encode() directly Function will encode the Chinese characters into the form of "\u***", since php5 This problem has been solved since .4. Use the following method to solve the problem of Chinese characters being encoded. json_encode("Chinese", JSON_UNESCAPED_UNICODE)

For example: 'Xu' becomes '\u80e5' after json_encode processing, and the final The Chinese part of json is replaced with unicode encoding. What we have to solve is to convert object to json and ensure that the Chinese inside the object still appears as normal Chinese in json. Now it seems that only using json_encode cannot achieve the goal.
My solution: first url encode (urlencode) the Chinese field in the class, then json encode (jsonencode) the object, and finally url decode (urldecode) json, which is the final json, and the Chinese inside is still the same It's the Chinese one!
The test code is as follows:

<?php 
class myClass { 
public $item1 = 1; 
public $item2 = &#39;中文&#39;; 
function to_json() { 
//url编码,避免json_encode将中文转为unicode 
$this->item2 = urlencode($this->item2); 
$str_json = json_encode($this); 
//url解码,转完json后将各属性返回,确保对象属性不变 
$this->item2 = urldecode($this->item2); 
return urldecode($str_json); 
} 
} 
$c = new myClass(); 
echo json_encode($c); 
echo &#39;<br/>&#39;; 
echo $c->to_json(); 
echo &#39;<br/>&#39;; 
echo json_encode($c); 
echo &#39;<br/>&#39;; 
echo json_encode(&#39;胥&#39;); 
?>
Copy after login

Program output result:

{"item1":1,"item2":"\u4e2d\u6587"} 
{"item1":1,"item2":"中文"} 
{"item1":1,"item2":"\u4e2d\u6587"} 
"\u80e5"
Copy after login

The above is the detailed content of Problem with json_encode Chinese encoding in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 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!