5
<?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 ?> 
4
  • 2
    Use a NOWDOC instead. Commented Dec 25, 2014 at 7:04
  • There's a variable in op code, NOWDOC will skip it. Use output buffering. Commented Dec 25, 2014 at 7:05
  • @mario changing EOT to 'EOT' works Commented Dec 25, 2014 at 7:09
  • 1
    show yourself downvoter Commented Dec 25, 2014 at 7:55

2 Answers 2

8

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;
Sign up to request clarification or add additional context in comments.

Comments

0

My code:

$javascript = <<<'EOT'
<script type="text/javascript">
$demo = 'test';
alert($demo);
</script>
EOT;
echo $javascript;

If i use 'EOT' then my code in javascript working well, but i use EOT then my code will understand $dem is variable in PHP

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.