Escaping/encoding single quotes in JSON encoded HTML5 data attributes

烈酒焚心 提交于 2019-12-28 02:45:21

问题


In PHP, I use json_encode() to echo arrays in HTML5 data attributes. As JSON requires - and json_encode() generates - values encapsulated by double quotes. I therefor wrap my data attributes with single quotes, like:

<article data-tags='["html5","jquery","php","test's"]'>

As you can see, the last tag (test's) contains a single quote, and using json_encode() with no options leads to parsing problems.

So I use json_encode() with the JSON_HEX_APOS parameter, and parsing is fine, as my single quotes are encoded, but I wonder: is there a downside doing it like this?


回答1:


You need to HTML escape data echoed into HTML:

printf('<article data-tags="%s">',
    htmlspecialchars(json_encode(array('html5', ...)), ENT_QUOTES, 'UTF-8'));



回答2:


or use the build-in option:

json_encode(array('html5', ...), JSON_HEX_APOS)

you can check it up in the manual: http://php.net/manual/en/json.constants.php#constant.json-hex-apos



来源:https://stackoverflow.com/questions/8832528/escaping-encoding-single-quotes-in-json-encoded-html5-data-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!