This question already has an answer here:
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.
encode it with JSON
I have had a similar issue and understand that the following is the best solution:
However, the link that micahwittman posted suggests that there are some minor encoding differences. PHP's
rawurlencode()
function is supposed to comply with RFC 1738, while there appear to have been no such effort with Javascript'sdecodeURIComponent()
.Micah's solution below worked for me as the site I had to customise was not in UTF-8, so I could not use json; I'd vote it up but my rep isn't high enough.
htmlspecialchars
Description
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.
This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application.
The translations performed are:
http://ca.php.net/htmlspecialchars
Don't run it though
addslashes()
; if you're in the context of the HTML page, the HTML parser can still see the</script>
tag, even mid-string, and assume it's the end of the JavaScript:Expanding on someone else's answer:
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.
Note that because
json_encode
escapes forward slashes, even a string that contains</script>
will be escaped safely for printing with a script block.