How to escape new line chars in php to output into a javascript string value?
javascript, php
Solution
<script type="text/javascript">
var myvar = <?php echo json_encode($value); ?>;
</script>
JSON == Javascript notation == the proper encoding/escaping method for any values output to Javascript.
Problem
I pulling out some html/text strings that I need to insert into a javascript variable. eg, that's how it would look in php: ``` echo "<script type=\"text/javascript\">\n"; echo "var myvar='{$value}'"; echo "\n</script>"; ``` The problem with the above approach is that some special characters would actually break the javascript code. So, I tried using htmlspecialchars: ``` htmlspecialchars($value,11,'utf-8',true); //11 stands for ENT_QUOTES|ENT_SUBSTITUTE ``` This did replace some unusual chars and most importantly the quotes. However the new line chars pass it by and break my javascript. So how could I escape the new line chars? I need to preserve them to be used later in the textareas. *EDIT* I will post a sample value of my variable. (They are actually the input from Tiny_mce) ``` <p>You've been...</p> <p><iframe src="http://www.youtube.com/embed/8d7OBluielc?wmode=transparent" frameborder="0" width="640" height="360"></iframe></p> ```