0

I want to serve my JSON-data via script-tag

<?php

  $myArray = array(
    'a' => 'Hello world!', 
    'b' => '</script>',
    'c' => 123.456,
  );

  $myJson = json_encode($myArray);

?>

<script id="mydata" type="application/json"><?=$myJson?></script>

and then I want to get back my JSON-data in Javascript:

try {

  var myArray = JSON.parse(document.getElementById('mydata').innerHTML);
  console.log(myArray);

} catch(e) {

  console.log(e.message);

}

How do I escape $myJson-string in PHP to avoid HTML-errors?

NoSkill
  • 718
  • 5
  • 15

1 Answers1

0

One way to achieve a similar result is to assign the JSON directly to a JS variable,

<script>
var myVariable = JSON.parse('<?php echo $myJson; ?>');
console.log('myVariable', myVariable);
</script>

But if you insist on doing it in the way you've mentioned, then you may escape it using htmlentities or htmlspecialchars and then do some dirty hacks mentioned in this post.

<script id="mydata" type="application/json"><?php echo htmlentities($myJson) ; ?></script>

<script>
var txt = document.createElement("textarea");
txt.innerHTML = document.getElementById('mydata').innerHTML;
console.log('Parsed', JSON.parse(txt.value));
</script>
Sohel Aman
  • 482
  • 4
  • 6