[PHP] A generic solution that returns NULL for JSON string decoding

Source: Internet
Author: User

/*--------------------------------------------------------------------------------------------------------

@ Black eyed poet <www.chenwei.ws>

--------------------------------------------------------------------------------------------------------*/

PHP uses the Json_decode () function to decode the JSON string, the first argument passes the string, the second argument is true, returns an array, or false to return an object. If NULL is returned, indicating an error, the output json_last_error (), the resulting integer value corresponding to the wrong hint.

Json_last_error () is more common than the integer 4, which is a JSON string that was incomplete before Json_decode, so syntax error.

Then must be the client to submit the individual characters affect the format of the JSON, you can use JS to filter, you can solve the general problem, mainly filter returns, spaces, HTML tags.

/*
* Filter function
* @ Black eyed poet <www.chenwei.ws>
*/functionHtmlEncode (str) {str= Str.replace (/\s+/ig, "); STR= Str.replace (/&/g, "); STR= Str.replace (/</g, "); STR= Str.replace (/>/g, "); STR= Str.replace (/(?: t| |v|r) *n/g, ' <br/> ');str = str.replace (/t/g, ' &nbsp; &nbsp; ‘); STR= Str.replace (/x22/g, ' &quot; ')); STR= Str.replace (/x27/g, ' & #39; '); STR= str.replace (/"/g," "")); returnstr;}

In this case, you must submit the JSON string data to the server-side processing, which can only be filtered by the client.

Other Json_decode ($STR) return null for some reasons:

1. $STR can only UTF-8 encoding

2. The element cannot end with a comma (unlike PHP's array)

3. Elements cannot use single quotation marks

4. There must be no spaces and \ n in the middle of the element value

If this is the case, it can be handled as above.

[PHP] A generic solution that returns NULL for JSON string decoding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.