How to replace/escape U+2028 or U+2029 characters in PHP to stop my JSONP API breaking

前端 未结 2 1034
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-01 06:15

Ok I am running a public JSONP API which the data is served from my PHP server. I just read this article:

  • JSON: The JavaScript subset that isn\'t (by Magnus Holm;
2条回答
  •  再見小時候
    2021-02-01 06:38

    It’s worth pointing out that this is no longer necessary.

    By default, json_encode() encodes all non-ASCII characters (including U+2028 & U+2029), and also escapes the forward slash, even though that does not need to be escaped by the JSON spec. It does no harm to escape it, and it can be safer in certain contexts. So, by default, these characters are escaped anyway.

    The JSON_UNESCAPED_UNICODE constant outputs unescaped Unicode, which can save bytes. However, just as the slash character is escaped because it can be dangerous in some contexts, so too U+2028 & U+2029 are also escaped, because they too are dangerous in some contexts. This was not the case at the time you asked your question: this feature has been added to PHP more recently.

    (These extra escapes can be turned off with JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_LINE_TERMINATORS, respectively.)

提交回复
热议问题