This question already has an answer here:
However, this doesn’t work when $myVarValue contains quotes or newlines.
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
$myVarValueencoded 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.
encode it with JSON
I have had a similar issue and understand that the following is the best solution:
<script> var myvar = decodeURIComponent("<?php echo rawurlencode($myVarValue); ?>"); </script>
However, the link that micahwittman posted suggests that there are some minor encoding differences. PHP’s
The paranoid version: Escaping every single character.
EDIT: The reason why
json_encode() may not be appropriate is that sometimes, you need to prevent
" to be generated, e.g.
<div onclick="alert(???)" />
<script> var myVar = <?php echo json_encode($myVarValue); ?>; </script>
<script> var myVar = <?= json_encode($myVarValue) ?>; </script>