Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is the a proper php function to echo javascript string?
I want to the php function to echo something like this:

<!--/* OpenX Interstitial or Floating DHTML Tag v2.8.7 */-->
<script type="text/javascript">// <![CDATA[
//<![CDATA[
var ox_u = 'extremely_long_url_string';
if (document.context) ox_u += '&context=' + escape(document.context);
document.write("<scr"+"ipt type='text/javascript' src='" + ox_u + "'></scr"+"ipt>");
//
// ]]></script>

I know I can put it all in one line and use \ to escape all the quotes BUT I'm looking for a more elegant & effective solution.

share|improve this question
2  
"<scr"+"ipt Why are you concatenating strings, where it isn't necessary? –  feeela Sep 16 '11 at 9:46
add comment

3 Answers

up vote 2 down vote accepted

Use HEREDOC:

$a=<<<BLA
<!--/* OpenX Interstitial or Floating DHTML Tag v2.8.7 */-->
<script type="text/javascript">// <![CDATA[
//<![CDATA[
var ox_u = 'extremely_long_url_string';
if (document.context) ox_u += '&context=' + escape(document.context);
document.write("<scr"+"ipt type='text/javascript' src='" + ox_u + "'></scr"+"ipt>");
//
// ]]></script>
BLA;

and then you can simply

echo $a;
share|improve this answer
add comment

Use the heredoc-syntax.

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped […].

share|improve this answer
4  
Or just put your JS between ?> and <?php. –  Rijk Sep 16 '11 at 9:42
add comment

There is nothing specific or only for JavaScript but every output feature works for JavaScript. You can just print the out of <?php ?> tag like

<?php 
session_start(); //just an example PHP code
?>
<!--/* OpenX Interstitial or Floating DHTML Tag v2.8.7 */-->
<script type="text/javascript">// <![CDATA[
//<![CDATA[
var ox_u = 'extremely_long_url_string';
if (document.context) ox_u += '&context=' + escape(document.context);
document.write("<scr"+"ipt type='text/javascript' src='" + ox_u + "'></scr"+"ipt>");
//
// ]]></script>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.