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.
If you use a templating engine to construct your HTML then you can fill it with what ever you want!
Check out XTemplates. It's a nice, open source, lightweight, template engine.
Your HTML/JS there would look like this:
You could try
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.or
You can insert it into a hidden DIV, then assign the innerHTML of the DIV to your JavaScript variable. You don't have to worry about escaping anything. Just be sure not to put broken HTML in there.