Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

php

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>

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.

Thanks in advance.

like image 527
agoldev Avatar asked Aug 19 '16 10:08

agoldev


1 Answers

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

like image 118
deceze Avatar answered Oct 07 '22 01:10

deceze