Home > Backend Development > PHP Tutorial > Old version of PHP's function to escape special characters in Json, escape json_PHP tutorial

Old version of PHP's function to escape special characters in Json, escape json_PHP tutorial

WBOY
Release: 2016-07-13 09:51:22
Original
919 people have browsed it

老版本PHP转义Json里的特殊字符的函数,转义json

在给一个 App 做 API,从服务器端的 MySQL 取出数据,然后生成 JSON。数据中有个字段叫 content,里面保存了文章内容,含有大量 HTML 标签,这个字段在转 json 的时候需要转义,因为有大量的特殊字符会破坏 json 的结构。

比如这么一段 content:

复制代码 代码如下:
'Lorem ipsum "dolor" sit amet, consectetur \ adipiscing elit.'

则必须要转化为:

复制代码 代码如下:
Lorem ipsum \"dolor\" sit amet,\nconsectetur \\ adipiscing elit.

如果 PHP 版本 > 5.2,json_encode 自带转义。如果是旧版本的 PHP 则可以用下面的函数。

# 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;
}
Copy after login

经常会用到,记录一下,希望对你有帮助。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1013719.htmlTechArticle老版本PHP转义Json里的特殊字符的函数,转义json 在给一个 App 做 API,从服务器端的 MySQL 取出数据,然后生成 JSON。数据中有个字段叫 conte...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template