Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

What is the easiest way to encode a PHP string for output to a JavaScript variable?

I have a PHP string that includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable.

Normally, I would just construct my JavaScript in a PHP file, à la:
<script>
var myvar = "<?php echo $myVarValue;?>";
</script>


However, this doesn't work when $myVarValue contains quotes or newlines.
by

2 Answers

rahul07
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.
sandhya6gczb
The following is the best solution:

<script>
var myvar = decodeURIComponent("<?php echo rawurlencode($myVarValue); ?>");
</script>

Login / Signup to Answer the Question.