用JSON编码的HTML5数据属性转义/编码单引号

时间:2021-10-06 22:29:41

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:

在PHP中,我使用json_encode()回显HTML5数据属性中的数组。由于JSON要求-和json_encode()生成用双引号封装的值。我在这里用单引号括起我的数据属性,比如:

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

如您所见,最后一个标记(测试)包含一个单引号,使用json_encode()而没有选项会导致解析问题。

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?

所以我使用json_encode()和JSON_HEX_APOS参数,解析没问题,因为我的单引号都是编码的,但是我想知道:这样做有什么不好的地方吗?

2 个解决方案

#1


50  

You need to HTML escape data echoed into HTML:

您需要HTML转义数据回显到HTML:

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

#2


8  

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

您可以在手册中查阅:http://php.net/manual/en/json.constants.php#constant.json-hex-apos

#1


50  

You need to HTML escape data echoed into HTML:

您需要HTML转义数据回显到HTML:

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

#2


8  

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

您可以在手册中查阅:http://php.net/manual/en/json.constants.php#constant.json-hex-apos