Output Encoded PHP String for Use in a Javascript Variable

The problem with just echoing a php sting for a javascript variable is escaping the sting properly for single and double quotes and line returns.  I found this fix for my problem with an apostrophe in the string that closed out the quote early.  This is a better option that trying to use  addslashes.  Use json_encode instead.

 var myvar = <?php echo json_encode($myVarValue); ?>;

reference: http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-and-escape-newlines

Scroll to Top