Search code examples
phpjavascriptvariablesechoquotes

Echoing javascript from PHP


I am trying to echo some google analytics javascript code from PHP so it can be conditionally read based on specific scenarios. I'm having difficulty wrapping my head around the quoting since the code contains /* */ characters. I'm looking for some direction in assigning this type of text to a php variable.

Thanks

$sJS .='<script type="text/javascript">';
$sJS .='/* <![CDATA[ */"';
$sJS .='var google_conversion_language = "en";';
$sJS .='var google_conversion_format = "2";';
$sJS .='var google_conversion_color = "ffffff";';
$sJS .='var google_conversion_value = 0;';
$sJS .='/* ]]> */';
$sJS .='</script>';
$sJS .='<script type="text/javascript" src="http://www.googleadservices.com/page.js">';
$sJS .='</script>';
$sJS .='<noscript>';
$sJS .='<div style="display:inline;">';
$sJS .='<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/997410413/?value=1.00&amp;label=ffr456dj5QIQ7YzN2wM&amp;guid=ON&amp;script=0"/>';
$sJS .='</div>';
$sJS .='</noscript>';

Solution

  • You don't need to do it line by line like that... PHP supports continuation to the next line. This works just fine:

    $sJS = '<script type="text/javascript">
        /* <![CDATA[ */
        var google_conversion_language = "en";
        var google_conversion_format = "2";
        var google_conversion_color = "ffffff";
        var google_conversion_value = 0;
        /* ]]> */
        </script>
        <script type="text/javascript" src="http://www.googleadservices.com/page.js">
        </script>
        <noscript>
        <div style="display:inline;">
        <img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/997410413/?value=1.00&amp;label=ffr456dj5QIQ7YzN2wM&amp;guid=ON&amp;script=0"/>
        </div>
        </noscript>';
    

    Your string is quoted with single quotes, there are no single quotes inside of it, and there are no backslashes or escape sequences.

    Visibly working (if you view source) at: http://gfosco.kodingen.com/phpjs.php