I'm trying to build a large JSON string in PHP and then echo it to the client like this. My problem is that the PHP function json_encode
isn't properly escaping characters for the purposes of javascript.
Here's my data:
my_table
------------------------------------------------------------------
| title | description |
------------------------------------------------------------------
| Something's "Fun" | Hello[invisible carriage return char]World |
------------------------------------------------------------------
There are three characters in these data that need to be escaped: the single quote, the double quote, and the carriage return character.
Here's my php that turns the data into json (after I put the data into an object):
$array = array(
'title' => obj->title,
'desc' => obj->description
);
$json = json_encode($array);
I then take my json string with the "properly" escaped characters and echo it to the client from my view like this:
<script>
var jsonString = '<?php echo $json; ?>';
var obj = JSON.parse(jsonString);
</script>
But when the page loads, my browser (Chrome) pushes an "Unexpected identifier" error because this is what the script tag actually looks like:
<script>
var jsonString = '{"title":"Something's \"Fun\"","desc":"Hello
World"}';
var obj = JSON.parse(jsonString);
</script>
From the perspective of js the double quote is the only one that's escaped correctly. The single quote isn't escaped at all and js freaks out at the .
BTW: manually escaping the single quote doesn't work. And I don't know what to do with the to get js to recognize it.