0

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?

Adam Baranyai
  • 3,635
  • 3
  • 29
  • 68
  • 1
    Well, storing a large json in html does not seem a very good idea itself :) You can `base64_encode`: this would increase size but definitely take away all the headache – Alexander Mikhalchenko Aug 12 '16 at 11:39
  • What other option do you propose then? I want to access this data via javascript later on, and I would like to ommit an unneccessary AJAX call if possible:| – Adam Baranyai Aug 12 '16 at 11:40
  • 1
    Possible duplicate of [Escaping/encoding single quotes in JSON encoded HTML5 data attributes](http://stackoverflow.com/questions/8832528/escaping-encoding-single-quotes-in-json-encoded-html5-data-attributes) – apokryfos Aug 12 '16 at 12:12
  • 1
    Slashes don't have any special meaning in HTML and I can't figure out why `htmlspecialchars()` wouldn't be enough to escape characters that are. Are you sure your diagnostic is correct? What exact problem are you facing? Can you edit the question and post sample data that reproduces the issue? – Álvaro González Aug 12 '16 at 12:23
  • a simple `htmlspecialchars()` just after encoding the array solved my problem. The only thing I didn't try:| – Adam Baranyai Aug 12 '16 at 12:43

1 Answers1

0

Storing a large json in html does not seem a very good idea itself :) If you want to access that via javascript you can declare a variable in <script> block:

<div id='map'></div>
<script type="text/javascript">
    var mapData = <?php echo json_encode($nodes); ?>;
</script>

Moreover, this way you get a significant performance improvement.

P.S. Yes, you get a global variable

Alexander Mikhalchenko
  • 4,525
  • 3
  • 32
  • 56