I have a large array in php, containing many sub-arrays. (Around ~100 sub-arrays, each containing nested arrays of level 3 at least, some of them with text which has '
and "
marks in them. I would like to json_encode()
this array, and store it an HTML data
element.
This is the code I've used to store the data in the html:
echo "<div id='map' data-nodes='".json_encode($nodes)."'></div>";
I've tried many different things, and can't seem to nail this one. My HTML breaks each time I try to add this large json string to it. The problem must be with the slashes somehow, but I can't figure out how to solve it.
What I've tried so far:
1. Adding htmlspecialchars()
, and/or addslashes()
separatly to the text sub-arrays.
2. Adding 'addslashes()' right after json encodeing the whole array
3. Changing the quotation marks in the echo from double slashes, to single slashes, and vice-versa
4. A mix of all four of these.
When I render the page, it can be clearly seen, that the data-nodes
HTML data element finishes early with a double quotation mark, and there is still text after it.
Any ideas what am I doing wrong?