Create an API for an App, extract data from MySQL on the server, and generate JSON. There is a field in the data called content, which stores the content of the article and contains a large number of HTML tags. This field needs to be converted to json...
Create an API for an App, extract data from MySQL on the server, and generate JSON. There is a field in the data called content, which stores the content of the article and contains a large number of HTML tags. This field needs to be escaped when converted to json, because a large number of special characters will damage the json structure.
For example, the following content:
'Lorem ipsum "dolor" sit amet, consectetur \ adipiscing elit.'
It must be converted:
Lorem ipsum \"dolor\" sit amet,\nconsectetur \\ adipiscing elit.
Which of the following characters must be escaped? See:
If the PHP version is later than 5.2, json_encode comes with an escape character. If it is an old 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;}
The above is the detailed content of the function for parsing special characters in PHP escape Json. For more information, see other related articles in the first PHP community!