json_encode Chinese display problem solution_PHP tutorial
Jul 13, 2016 am 10:57 AMThe Chinese display problem of json_encode in PHP is a problem that troubles many programmers. Now I will introduce two solutions to the Chinese display problem for your reference.
Json has become the most commonly used data format in current web development. PHP also supports the json and array conversion functions json_encode and json_decode starting from 5.2. But during use, we will find that (the Chinese character "you" is taken as an example below) the Chinese converted by the json_encode function has all become an encoding similar to u4f60 (you). Although it does not affect program execution, it is very unintuitive
First of all, json_encode converts Chinese into the corresponding hexadecimal representation of unicode code u4f60, (similar to the escape function of js (%u4f60)), that is, 0x4f60. Therefore, we only need to convert the unicode code (UCS-2) into utf-8 encoded Chinese characters. The function is as follows:
The code is as follows
|
Copy code
|
||||
/**
|
The code is as follows | Copy code |
/** * Urlencode arrays and scalars * Usually call wphp_json_encode() * Handle json_encode Chinese display problem * @param array $data * @return string */ function wphp_urlencode($data) { if (is_array($data) || is_object($data)) { foreach ($data as $k => $v) { if (is_scalar($v)) { If (is_array($data)) { $data[$k] = urlencode($v); } else if (is_object($data)) { $data->$k = urlencode($v); } } else if (is_array($data)) { $data[$k] = wphp_urlencode($v); //Call this function recursively } else if (is_object($data)) { $data->$k = wphp_urlencode($v); } } } return $data; } /** * json encoding * * Solve the problem that the Chinese display after json_encode() processing is not intuitive * By default, "Chinese" will be changed to "u4e2du6587", which is not intuitive * If there are no special needs, it is not recommended to use this function. It is better to use json_encode directly and save resources * json_encode() can only work properly when the parameter encoding format is UTF-8 * * @param array|object $data * @return array|object */ function ch_json_encode($data) { $ret = wphp_urlencode($data); $ret = json_encode($ret); return urldecode($ret); } |

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
