Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write PHP inside JavaScript inside PHP? [duplicate]

Tags:

javascript

php

Inside a PHP script I have this:

echo <<<EOD

<script type="text/javascript">
document.getElementById('my_element_id').innerHTML='Do stuff';
</script>

EOD;

Can I add PHP inside the JavaScript? Replace the "Do stuff" part with PHP code? If yes, how do I do it?

like image 238
Malasorte Avatar asked Jun 12 '26 09:06

Malasorte


1 Answers

First of all, it should be noted that this has nothing to do with javascript. You could have any form of text. Your actual question is how to use a variable inside of a heredoc.

Heredoc is defined as the following:

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.

Meaning that since this works:

$name = 'Foo';

echo "My name is $name"; // Using double quotes so variables get expanded

Then this also works:

$name = 'Foo';

echo <<<EOD
    My name is <strong>$name</strong>
EOD;  // Using heredoc so variables get expanded

Essentially meaning that yes, as long as you put your 'Do stuff' content into a variable first. Note that if you use more advanced variables/arrays, it's a good idea to do a $array = json_encode($array) before pasting it into JS code (imagine if $name was The Boss's Wife - then the apostrophe would ruin your JS if you don't encode it).

DEMO

like image 115
h2ooooooo Avatar answered Jun 14 '26 22:06

h2ooooooo