Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP parses JavaScript content inside heredoc

<?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 ?> 
like image 834
user1643156 Avatar asked Dec 25 '14 06:12

user1643156


1 Answers

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;
like image 184
deceze Avatar answered Nov 11 '22 23:11

deceze