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


Escaping/encoding single quotes in JSON encoded HTML5 data attributes

在PHP中,我使用json_encode()来回显HTML5数据属性中的数组。由于JSON需要-并且json_encode()生成-用双引号封装的值。因此,我用单引号包装我的数据属性,比如:

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

正如您所看到的,最后一个标记(测试的)包含一个引号,并且在没有选项的情况下使用json_encode()会导致解析问题。

所以我使用json_encode()JSON_HEX_APOS参数,解析是可以的,因为我的单引号是编码的,但我想知道:这样做有缺点吗?

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

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

或使用内置选项:

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

您可以在手册中查看:http://php.net/manual/en/json.constants.php#constant.json-十六进制apos