PHP code inside a Javascript's "document.write()"

user411103 picture user411103 · Aug 13, 2012 · Viewed 51.5k times · Source

I need to write some PHP code inside a Javascript's "document.write()". This is a dummy example, but in the future Javascript will generate automatically that PHP code.

This is the Hello World I have coded:

MyFile.php

<html>
<body>
<script type="text/javascript">
document.write("<?php echo \"Hello World\"; ?>");
</script>
</body>
</html>

However, nothing is displayed, and in the DOM file I get this:

<html>
<body>
<script type="text/javascript">
<!--?php echo  "Hello World"; ?-->
</script>
</body>
</html>

Any help? Thanks

Answer

wanovak picture wanovak · Aug 13, 2012

The PHP gets evaluated before the JavaScript, so no need to escape the quotes.

document.write("<?php echo "Hello World"; ?>");