Encounter problems:
When we use json_encode($res) to convert the array to a json string in the project development, but the returned result is blank, what should we do at this time?
Solution:
1. To find the cause of the error, you can use the two methods that come with PHP to check the error
json_last_error()
This function will return the cause of the current json_encode error. It returns a number. You need to see which error it is.
error code | Codename | description | |
0 | JSON_ERROR_NONE |
No error occurred | |
1 | JSON_ERROR_DEPTH |
Maximum stack depth reached | |
2 | JSON_ERROR_STATE_MISMATCH |
Invalid or abnormal JSON | |
3 | JSON_ERROR_CTRL_CHAR |
The control character is wrong, it may be the wrong encoding | |
4 | JSON_ERROR_SYNTAX |
Grammatical errors | |
5 | JSON_ERROR_UTF8 |
Abnormal UTF-8 characters, maybe because of incorrect encoding. | PHP 5.3.3 |
6 | JSON_ERROR_RECURSION |
One or more recursive references in the value to be encoded | PHP 5.5.0 |
7 | JSON_ERROR_INF_OR_NAN |
One or more NAN or INF values in the value to be encoded |
PHP 5.5.0 |
8 | JSON_ERROR_UNSUPPORTED_TYPE |
The value of the specified type cannot be encoded. | PHP 5.5.0 |
9 | JSON_ERROR_INVALID_PROPERTY_NAME |
The specified attribute name cannot be encoded. | PHP 7.0.0 |
10 | JSON_ERROR_UTF16 |
Malformed UTF-16 characters may be due to incorrect character encoding. | PHP 7.0.0 |
json_last_error_msg()
This function will return an explanation of the reason for the error, for example: Malformed UTF-8 characters, possibly incorrectly encoded
Malformed UTF-8 characters, possibly incorrectly encoded This error is generally caused by some special Chinese transcoding garbled characters in the utf-8 encoding. Just retranslate the utf-8 encoding. The method is as follows:
//转换字符编码
$result = mb_convert_encoding($result, 'utf-8', 'UTF-8,GBK,GB2312,BIG5');