Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate] Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate] php php

Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]


Expanding on someone else's answer:

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

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.


function escapeJavaScriptText($string){    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));}