PHP > JavaScript JSON

March 4th, 2021

Outputting a JSON string from PHP into a JS script for consumption as a JS object via JSON.parse can be annoyingly difficult to achieve. Lots of solutions online suggest esoteric regex functions, or chains of encoding functions - but there's an easy solution, at least since PHP 5.3ish...

Just use the JSON_HEX_QUOT flag in the json_encode function in PHP when outputting inside your JS/HTML file.

e.g.

var assets = JSON.parse(f_assets, JSON_HEX_QUOT);}
else {     echo "[]";} ?>);