The old version of PHP escapes the special characters in JSON function, escaped json_php tutorial

Source: Internet
Author: User

The old version of PHP escapes the special characters in JSON functions, escaping JSON


Make an API for an App, pull the data from the server-side MySQL, and then generate the JSON. There is a field in the data called content, which holds the content of the article, contains a lot of HTML tags, this field should be escaped when the JSON is transferred, because there are a large number of special characters will destroy the structure of the JSON.

Such a content:

Copy the Code code as follows:
' Lorem ipsum ' dolor ' sit amet, consectetur \ adipiscing elit. '

It must be converted to:

Copy the Code code as follows:
Lorem ipsum \ "dolor\" sit amet,\nconsectetur \ adipiscing elit.

If PHP version > 5.2,json_encode comes with Escape. If you have an older version of PHP, you can use the following function.

# list from www.json.org: (\b Backspace, \f formfeed) public Function escapejsonstring ($value) {  $escapers = array ("\ \" , "/", "\" "," \ n "," \ r "," \ T "," \x08 "," \x0c ");  $replacements = Array ("\\\\", "\\/", "\\\" "," \\n "," \\r "," \\t "," \\f "," \\b ");  $result = Str_replace ($escapers, $replacements, $value);  return $result;}

Often use, record, hope to help you.

http://www.bkjia.com/PHPjc/1013719.html www.bkjia.com true http://www.bkjia.com/PHPjc/1013719.html techarticle The old version of PHP escapes the special characters in the JSON function, escaping JSON in an API for an App, extracting the data from the server-side MySQL, and then generating the JSON. There is a field in the data called Conte ...

  • 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.