Anonymous Anonymous - 1 year ago 209
PHP Question

Pass a PHP string to a JavaScript variable (and escape newlines)

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:

var myvar = "<?php echo $myVarValue;?>";

However, this doesn't work when
contains quotes or newlines.

Answer Source

Expanding on someone else's answer:

  var myvar = <?php echo json_encode($myVarValue); ?>;

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $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.