What is the easiest way to encode a PHP string for output to a JavaScript variable?
I have a PHP string which 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.
Expanding on someone else's answer:
<script>
var myvar = <?= json_encode($myVarValue, JSON_UNESCAPED_UNICODE); ?>;
</script>
Using json_encode() requires:
$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.
Please note that if you use this in html attributes like onclick, you need to pass the result of json_encode to htmlspecialchars(), like the following:
htmlspecialchars(json_encode($string), ENT_QUOTES);
or else you could get problems with, for example, &bar;
in foo()&&bar;
being interpreted as an HTML entity.