How to convert php heredoc to javascript variable?

How to convert PHP HEREDOC to a JavaScript variable. I have a PHP variable with some special characters.

PHP:

$text = <<<EOD
line 1
line 2
line 3
EOD;

in javascript:

var text = '<?php echo $text ?>';
+4
source share
1 answer

Use json_encode()to convert PHP values ​​to Javascript literal:

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

This works because the JSON format is a subset of the Javascript syntax. It will correctly indicate the strings and escape characters to be escaped.

+4
source

All Articles