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

Javascript Nov 13, 2022

Requirement:

How may a PHP string be most simply encoded for output to a JavaScript variable?

We have a PHP string that contains quotation marks and newlines. The contents of this string must be placed in a JavaScript variable.

Solution:

Use json_encode()

<script>
  var newVar = <?php echo json_encode($varValue); ?>;
</script>

It requires:

  • PHP 5.2.0 or greater
  • $varValue encoded as UTF-8 (or US-ASCII)

Thanks!

Tags

Anurag Deep

Logical by Mind, Creative by Heart