How to output JavaScript with PHP

You should escape the JavaScript string delimiters inside the PHP string. You're using double quotes for both PHP and JavaScript strings. Try like this instead:

<html>
<body>
<?php

// Here, we use single quotes for PHP and double quotes for JavaScript
echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';

?>
</body>
</html>

You have to escape quotes on both JavaScript and PHP when the string delimiter are the same as the quotes:

echo "\""; // escape is done using a backslash
echo '\'';

Same in JavaScript:

alert("\""); // escape is done using a backslash
alert(echo '\'');

But because it's very hard to read a string with such escape sequences, it is better to combine single with double quotes, as needed:

echo '"';
echo "'";

The error you get if because you need to escape the quotes (like other answers said).

To avoid that, you can use an alternative syntax for you strings declarations, called "Heredoc"

With this syntax, you can declare a long string, even containing single-quotes and/or double-quotes, whithout having to escape thoses ; it will make your Javascript code easier to write, modify, and understand -- which is always a good thing.

As an example, your code could become :

$str = <<<MY_MARKER
<script type="text/javascript">
  document.write("Hello World!");
</script>
MY_MARKER;

echo $str;

Note that with Heredoc syntax (as with string delimited by double-quotes), variables are interpolated.


Another option is to do like this:

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

and if you want to use PHP inside your JavaScript, do like this:

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

Hope this can help.


An easier way is to use the heredoc syntax of PHP. An example:

<?php

echo <<<EOF
<script type="text/javascript">
    document.write("Hello World!");
</script>
EOF;

?>

You need to escape your quotes.

You can do this:

echo "<script type=\"text/javascript\">";

or this:

echo "<script type='text/javascript'>";

or this:

echo '<script type="text/javascript">';

Or just stay out of php

<script type="text/javascript">