The problem is simple to understand and demonstrate.
This code works fine:
<?php
$title = array("dfg","sdfsdg","asfas","Sdfh","Ssdth","Csdgo");
$title_json = json_encode($title);
?>
<script>
var obj = JSON.parse('<?= $title_json; ?>');
console.log(obj);
</script>
This code does not:
<?php
$title = array("Is President Trump still using his old Android phone?","Trump sets a dizzying WH pace in first days","Trumps White House Charm Offensive a Contrast to Solitary Obama","The inside story of a basketball teen so tall, he doesn't look real","Scientists say they are closer to making Star Wars holograms","Sperm theft lawsuit leaves appeals court weighing how much a life is worth","Call it Smunday: Heinz pushing to make Super Bowl Monday a national holiday");
$title_json = json_encode($title);
?>
<script>
var obj = JSON.parse('<?= $title_json; ?>');
console.log(obj);
</script>
Outputs error in console: Uncaught SyntaxError: missing ) after argument list - (index):20
where line 20 is one with JSON.parse and if you look at the source code of the page, the line reads:
var obj = JSON.parse('["Is President Trump still using his old Android phone?","Trump sets a dizzying WH pace in first days","Trump's White House Charm Offensive a Contrast to Solitary Obama","The inside story of a basketball teen so tall, he doesn't look real","Scientists say they are closer to making 'Star Wars' holograms","Sperm theft lawsuit leaves appeals court weighing how much a life is worth","Call it 'Smunday': Heinz pushing to make Super Bowl Monday a national holiday"]');
You may notice that the two code samples are exactly the same, the arrays even have the same length, the only difference is that the strings are longer in the second one. Does this mean there's a maximum length to the strings that can be parsed by JSON?
Your JSON data contains '
. So if you inject that data into a '
delimited string literal, that string literal will be closed prematurely and cause a syntax error. Simple example:
var foo = '{"key": "This key's value"}';
You should notice that if you look at the generate JavaScript source.
There is no need to use JSON.parse
here. The injected JSON can be interpreted as a JavaScript object/array literal:
var obj = <?= $title_json; ?>;
See also: How to pass variables and data from PHP to JavaScript?