


Detailed explanation of PHP json_encode() function and Chinese garbled code problem
Using the json_encode() built-in function in php (php > 5.2) can be used so that data in php can be transferred and used well with other languages.
The function of this function is to convert numerical values into json data storage format.
<?php $arr = array ( 'Name'=>'希亚', 'Age'=> ); $jsonencode = json_encode($arr); echo $jsonencode; ?>
The program running result is as follows:
{"Name":null,"Age":}
json_encode function Chinese is encoded as null. I googled it and found that it is very simple. In order to closely integrate with the front-end, Json only supports utf- encoding. I think it is because the front-end Javascript is also utf-.
<?php $array = array ( 'title'=>iconv('gb','utf-','这里是中文标题'), 'body'=>'abcd...' ); echo json_encode($array); ?>
The running result of this program is:
{"title":"\u8fd9\u91cc\u662f\u4e2d\u6587\u6807 \u9898","body":"abcd..."}
All Chinese characters in the array are missing or \u2353 etc. appear after json_encode.
The solution is to use the urlencode() function to process the following. Before json_encode, use urlencode() to process all the contents of all arrays, then use json_encode() to convert it into a json string, and finally use urldecode () Convert the encoded Chinese back.
<?php /************************************************************** * * 使用特定function对数组中所有元素做处理 * @param string &$array 要处理的字符串 * @param string $function 要执行的函数 * @return boolean $apply_to_keys_also 是否也应用到key上 * @access public * *************************************************************/ function arrayRecursive(&$array, $function, $apply_to_keys_also = false) { static $recursive_counter = ; if (++$recursive_counter > ) { die('possible deep recursion attack'); } foreach ($array as $key => $value) { if (is_array($value)) { arrayRecursive($array[$key], $function, $apply_to_keys_also); } else { $array[$key] = $function($value); } if ($apply_to_keys_also && is_string($key)) { $new_key = $function($key); if ($new_key != $key) { $array[$new_key] = $array[$key]; unset($array[$key]); } } } $recursive_counter--; } /************************************************************** * * 将数组转换为JSON字符串(兼容中文) * @param array $array 要转换的数组 * @return string 转换得到的json字符串 * @access public * *************************************************************/ function JSON($array) { arrayRecursive($array, 'urlencode', true); $json = json_encode($array); return urldecode($json); } $array = array ( 'Name'=>'希亚', 'Age'=> ); echo JSON($array); ?>
It was successful this time, the running results are as follows:
{"Name":"Xia","Age":"20 "}
The following will introduce to you the solution to Chinese garbled characters in PHP json_encode
I believe that many people have encountered the problem of Chinese garbled characters when using Ajax to interact with the background php page. As a lightweight data exchange format, JSON is very popular. However, using PHP as the background interaction is prone to the problem of Chinese garbled characters. JSON is the same as js. The characters on the client are processed in the form of UTF8. That is to say, when using JSON as the data format for submission and reception, the characters are processed by UTF8 encoding. When our page encoding and database encoding are not When using UTF8, it is extremely easy for Chinese garbled characters to appear. The solution is naturally to use UTF8 when processing JSON data with js or PHP.
PHP5.2 or above uses json_encode as a built-in function, which brings great convenience to website makers. However, we must note that json_encode only supports UTF8-encoded characters. Otherwise, Chinese characters will be garbled. Or a null value appears.
The solution is divided into the following two steps.
Step1
Ensure that characters are encoded in UTF8 when processing JSON. Specifically, we can change both the database encoding and page encoding to UTF8. Of course, if you like to use gbk encoding, you can convert the characters to UTF8 before JSON processing. There are the following methods in PHP:
<?php $data="JSON中文"; $newData=iconv("GB2312","UTF-8//IGNORE",$data); echo $newData; //ignore的意思是忽略转换时的错误,如果没有ignore参数,所有该字符后面的字符都不会被保存。 //或是("GB2312","UTF-8",$data); ?>
Step2
Backend PHP page (the page is encoded as UTF-8 or the characters have been converted to UTF -8) Use json_encode to convert the array array in PHP into a JSON string. For example:
<?php $testJSON=array('name'=>'中文字符串','value'=>'test'); echo json_encode($testJSON); ?>
The output result is:
{"name":"\u4e2d\u6587\u5b57\u7b26\u4e32″, "value":"test"}
It can be seen that even if UTF8-encoded characters are used, Chinese garbled characters appear when using json_encode. The solution is to use the urlencode() function to process the characters before using json_encode, then json_encode them, and use the urldecode() function to convert them back when outputting the results. The details are as follows:
<?php $testJSON=array('name'=>'中文字符串','value'=>'test'); //echo json_encode($testJSON); foreach ( $testJSON as $key => $value ) { $testJSON[$key] = urlencode ( $value ); } echo urldecode ( json_encode ( $testJSON ) ); ?>
Check the output result:
{"name":"Chinese string","value":"test ”}
At this point, Chinese characters have been successfully output. Feel free to use json_encode. In this way, the JSON string output in the PHP background will not appear Chinese garbled when eval is received by Ajax in the front-end javascript, because js also processes JSON format data in the form of UTF8, which is similar to PHP, so it receives the PHP page The JSON string does not cause problems.
For more detailed explanations of the PHP json_encode() function and articles related to Chinese garbled characters, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
