6 years ago (2015-04-05)  Software development |   First to comment  572 
post score 0 times, average 0.0

Because in the Android software development practice, the author wanted to add software update services to the software, so decided to rely on their own virtual host, use php to create an own API.Then output the query result of the database through the json standard format.

First, examples show

The simple form of API production code is:

The jsons_encode function to convert the array to json format will find the Chinese garbled shape like this: u901au8bafu5f55uff0cu662fu738bu67cfu5143u81eau4e3bu5f00 After the database was coded, the author discovered that this was a problem with the jsons_encode function. The causes were as follows:

Second, the reason analysis:

MySQL does not store unicode characters when storing into a database: MySQL only supports basic multilingual flat characters (0x0000-0xFFFF).Try to store a synonym instead :) Update: On MySQL 5.5.3 (which hasn't GA yet), support for supplemental characters if you use UTF8MB4 encoding. When json_encode is in Chinese, each Chinese character is encoded into "uxxxx", and when it is stored in the database, "" is blocked and becomes "uxxxx" directly.

Third, solve the problem:

1. Avoid json_encode converting Chinese unicode encoding.

PHP5.4 has added an option to Json: JSON_UNESCAPED_UNICODE.Adding this option will not automatically encode Chinese. $json= json_encode("Wang Baiyuan's blog", JSON_UNESCAPED_UNICODE);

2. First the Chinese field urlencode, json_encode, then urldecode, can also ensure that the Chinese will not be converted into unicode.

$json=urldecode(json_encode(array('brief'=>urlencode('Wang Boyuan's blog),'title'=>urlencode(Wang Baiyuan's blog)));

Fourth, the code to solve the problem

The above analyzes the cause of the problem. If your PHP version is 5.4 or above, you can use the solution above. The second solution is a general solution. Here's my own code for your reference:



This article has been printed on copyright and is protected by copyright laws. It must not be reproduced without permission.If you need to reprint, please contact the author or visit the copyright to obtain the authorization. If you feel that this article is useful to you, you can click the "Sponsoring Author" below to call the author!

Reprinted Note Source: Baiyuan's Blog>>https://wangbaiyuan.cn/en/php-using-json-encode-an-array-of-chinese-characters-2.html

Post comment


No Comment


Forget password?