This article mainly introduces how PHP can handle Json string decoding and return NULL. it uses an example of a filter function to demonstrate how to handle json return errors, and lists the common causes of this error. if you need a friend, refer to the example in this article to describe how PHP processes Json string decoding and returns NULL. Share it with you for your reference. The specific method is as follows:
In general, php uses the json_decode () function to decode json strings. if the first parameter is set to true, an array is returned. if the second parameter is set to false, an object is returned. If NULL is returned, an error is returned. the json_last_error () is output, and the error message corresponding to the obtained integer is displayed. As shown in:
Json_last_error () is a common integer 4, which is a syntax error because the json string is incomplete before json_decode.
Therefore, some characters submitted by the client may affect the json format. JS can be used for filtering to solve general problems, mainly filtering carriage return, spaces, and html tags.
The implementation code is as follows:
/** Filter function */function htmlEncode (str) {str = str. replace (/\ s +/ig, ''); str = str. replace (// g, ''); str = str. replace (//G, ''); str = str. replace (/(? : T | v | r) * n/g ,'
'); Str = str. replace (/t/g, ''); str = str. replace (/x22/g, '"'); str = str. replace (/x27/g, '''); str = str. replace (/"/g," "); return str ;}
In this case, you must submit the json string data to the server for processing and filter it only on the client.
Other causes for returning NULL in json_decode ($ str:
1. $ str can only be UTF-8 encoded
2. the element cannot end with a comma (different from the php array)
3. elements cannot use single quotes
4. element values cannot have spaces and must be replaced.
If you have encountered the above situation, you can follow the above methods. I hope this article will help you with PHP programming.