Expanding on someone else’s answer:
<script> var myvar = <?= json_encode($myVarValue, JSON_UNESCAPED_UNICODE); ?>; </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.
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:
or else you could get problems with, for example,
foo()&&bar; being interpreted as an HTML entity.