Search code examples
phpjavascriptescapingquotes

Problems with quotes when writing javascript code in PHP


I wonder what's the best method for writing javascript code into a PHP variable?

Some times it might be quite long javascript code... Is there a way without escaping all quotes?

<?php
echo '
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">

a_div.innerHTML = '<iframe style="width:100%;height:300px;" id="iframe_upload" src="index.php">';

</script>'

?>

Solution

  • Use heredoc. For example:

    $var = EOF<<<
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript">
    a_div.innerHTML = '<iframe style="width:100%;height:300px;" id="iframe_upload" src="index.php">';
    </script>
    EOF;
    

    The EOF can be any arbitrary string you want, it just has to come directly after the <<< delimiter and match on both sides of the string you want to create.