Toni Toni - 10 months ago 39
JSON Question

Will php's json_encode() always use double quotes as string delimiter?

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"}'>

The question is, can I rely on the
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.

Thanks in advance.


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>

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