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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8832528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:36:23  来源:igfitidea点击:

Escaping/encoding single quotes in JSON encoded HTML5 data attributes

phpjsonhtmlcustom-data-attribute

提问by Jérémy F.

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.

如您所见,最后一个标签(test's)包含一个单引号,json_encode()不带选项使用会导致解析问题。

So I use json_encode()with the JSON_HEX_APOSparameter, 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参数,并解析是好的,因为我的单引号进行编码,但我不知道:有一个缺点做这样的吗?

回答by deceze

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'));

回答by Picard

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