php的json_encode()始终使用双引号作为字符串定界符吗?
我有一个包含字符串作为值的php关联数组,并将其编码为JSON并将其存储在html-data属性中.那是一些JS读取的.
I have a php associative array containing strings as values and I encode it to JSON and store it in an html-data attribute. That is read by some JS.
到目前为止,一切都很好.
So far so good.
现在,我需要对数据属性使用单引号,否则上下文会切换.
Now, I need to use single quotes for the data attribute, otherwise the context switches.
<section id="settings" data-settings='{"some":"val"}'>
</section>
问题是,我可以依靠php的json_encode()
函数来始终对字符串进行双引号编码吗?令人惊讶的是,我似乎找不到任何信息.我只从那些对数组值中的引号有疑问的人那里找到文章.
The question is, can I rely on the json_encode()
function of php to encode strings always with double quotes? Surprisingly, I can't seem to find information on this. I only find articles from people having issues with quotes in the array values.
谢谢.
是的,如JSON规范中所定义,定界符将始终为"
.但是,值可能包含'
字符,这会破坏HTML.为简单起见,而不用担心可能会造成问题的原因,请 HTML转义您的价值观!
Yes, as defined in the JSON spec, the delimiter will always be "
. However, values may contain '
characters, which would break your HTML. To keep it simple and not worry about what might or mightn't pose an issue, HTML-escape your values!
<section data-settings="<?= htmlspecialchars(json_encode($foo)); ?>"></section>
无论输入什么值或如何对其编码,都保证此方法始终有效.请注意,默认情况下, htmlspecialchars
仅会编码"
,而不是'
;因此您必须使用"
作为HTML中的分隔符(或更改默认的转义行为).
This is guaranteed to work, always, no matter what values you pipe in or how you encode them. Note that htmlspecialchars
will by default only encode "
, not '
; so you must use "
as the delimiter in HTML (or change the default escaping behavior).