2

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.

1
  • 2
    "<scr"+"ipt Why are you concatenating strings, where it isn't necessary? Commented Sep 16, 2011 at 9:46

3 Answers 3

4

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 […].

Sign up to request clarification or add additional context in comments.

1 Comment

Or just put your JS between ?> and <?php.
3

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;

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.