How to escape text coming from PHP in JavaScript?

escaping, html-escape-characters, javascript, jquery, string-literals

Solution

simply use json_encode:

var playlistacting = <?php echo json_encode($this->result);?>;

Problem

I am using jPlayer to display some videos and I create the playlist on the fly in a php foreach statement: ``` var playlistacting = [ <?php foreach($this->result as $val){?> { title: '<?php echo $val->getTitle();?>', artist: '<?php echo $val->getDes();?>', poster: "<?php echo $val->getVideoId();?>.jpg", thumb: "<?php echo $val->getVideoId();?>.jpg", flv: "<?php echo $val->getVideoId();?>.flv", }, <?php }?> ]; ``` and `$val->getDes()` example would be `I have a one-hour (approximately) solo musical revue called "Manhattan With A Twist". The entire...` the error I get is ``` unterminated string literal [Break On This Error] artist: 'I have a one-hour (approximately)solo musical revue called "Manhattan W... jquery.js (line 2, col 32) ``` and is poining to the `'` at the beginning of the string. I can do this: `title: "<?php echo htmlspecialchars($val->getTitle());?>",` and I will get the same error but with `"` instead of `'`. I'm not sure what is happening here. Is it complaining about that `'` not being escaped or what? Any ideas?

Original source