0

How do I insert a formatted javascript to have newline in php?

I want my script to display this way but I can't seem to echo newlines.

The script is inserted into the html in one line.

<script>
  var a;
  var b;
</script>

It comes out this way:

<script> var a; var b; </script>

How can i do this ?

3
  • already tried it but still got a script inserted as one line. I tried using " and ' but it didn't work. Commented Mar 26, 2014 at 11:35
  • Really? codepad.org/TW2ycnPE Commented Mar 26, 2014 at 11:38
  • Why is this PHP related? Please post the php-related part of your code. How do you insert your code? Commented Mar 26, 2014 at 11:38

5 Answers 5

2

If you want indention in html source you can use \n. For example-

echo "\n<script> \n\tvar a;\n\tvar b; \n</script>";

Or you can use, as already posted by Laukik

<?php
echo <<<HTML_ENTITIES
<script>
  var a;
  var b;
</script>
HTML_ENTITIES;
?>

Which will produce the source like-

<script>
  var a;
  var b;
</script>

Or if you want this in design than use <pre></pre> tag at start of your javascript code on the page where you want to show your code, than you will get same indention of html for particular script section.

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

Comments

0

Try with

<?php
echo <<<HTML_ENTITIES
<script>
  var a;
  var b;
</script>
HTML_ENTITIES;
?>

3 Comments

sorry. Just inserted your code and it inserted the code correctly. I'm using adsense and the <ins> part isn't formatted correctly how do I correct it.
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-xxxxxxxxxxx" data-ad-slot="xxxxxxxx"> </ins>
what are you getting in output with your code now and what do you want in output?
0

if you are printing from your script tag from php use echo \n var a; \n var b; \n ;

Comments

0

You could jump in and out of php like this:

?>
<script>
  var <?php echo "a"; ?>;
  var <?php echo "b"; ?>;
</script>
<?php

Just substitute the "a" and "b" strings with the actual variables you want to output.

1 Comment

Opposed to a version where you echo it all out in one big string, e.g. <?php echo "<script>var a; var b;</script>";?> This has the extra benefit that your editor will know which part of your code is javascript and which is php, so that you can enjoy stuff like syntax highlighting and autocomplete.
-1

Use pre tag at start of your php page than you will get same indention of html for whole document including Script tag.

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.