<?php
$javascript = <<<EOT
<script type="text/javascript">
function test () {
return 'test test test \n test test test';
}
</script>
EOT;
echo $javascript;
?>
The \n above is parsed as newline by PHP, generates HTML source like the following
return 'test test test
test test test';
and this results in a JavaScript syntax error: unterminated string literal.
I have a big chunk of JavaScript code, so I don't want to wrap them like
$javascript = "<script type=\"text/javascript\">\nfunction test()...\n";
and actually the JavaScript code is not directly echo'd to the page, it is passed to another function, this is why I need a PHP variable.
So how can I define a PHP variable that contains a big chunk of JavaScript code whitout causing problems?
Is there a way like if / endif?
<?php if (condition): ?>
html code...
<?php endif ?>
Option 1: Use a NOWDOC, which is to HEREDOCs as '
single quotes are to "
double quotes.
$javascript = <<<'EOT'
...\n...
EOT;
Option 2: Escape the special character:
$javascript = <<<EOT
...\\n...
EOT;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With