This is similar to PHP generated content inside Javascript breaking script, however I'm not able to understand where I'm wrong.
Here is the brief. I'm trying to output 10 strings from MySQL DB into a javascript array s, (s[1] to s[10]) (stored in one MySQL table under columns pt1 to pt1 - info so code is understandable to all). (Note $apos is just the apostrophe string - not a concern here).
<?php
echo "<script>\n";
echo "var s = [];\n";
for($i=1;$i<=10;$i++) {
echo "s[".$i."] = ".$apos.$r['pt'.$i].$apos.";\n";
}
echo "</script>";
?>
It produces the right code when I look at the source by 'View Source' in browser:
<script>
var s = [];
s[1] = 'a';
s[2] = 'b';
.
.
s[10] = 'j';
</script>
However, this doesn't work as a script (meaning if I check in Google developer tools, and I click on content inside the 'script' tag elements, it is told to be 'text', and not 'script' in the bar below).
However if I remove the PHP, and manually write the whole script the same way, it works just fine. I have tried removing the \n linebreaks in the PHP code, but still the same problem.
Something in PHP is breaking the script. Can you help?
var s=<?php echo json_encode($info);?>;