-1

Sample PHP code

wolf@linux:~$ cat 1-new-line.php 
<?php
echo "Hello
World
Foo Bar!";

$aString = '
First Line
Second Line
Third Line';
echo $aString;
?>

wolf@linux:~$

It runs as expected in CLI

wolf@linux:~$ php 1-new-line.php 
Hello
World
Foo Bar!
First Line
Second Line
Third Line
wolf@linux:~$ 

But not via browser

enter image description here

What's wrong in this code? How to render it properly in web browser?

2 Answers2

3

Browsers interpret PHP's output as HTML, and in HTML newlines get replaced by spaces.

If you want to learn how to line-break in a browser, use <br /> or wrap sentences in <p> tags.

You can also tell a browser to treat your output as text, and not HTML. In that case, use the following header (before any output):

header('Content-Type: text/plain');
Evert
  • 93,428
  • 18
  • 118
  • 189
  • Thanks @Evert. Can you show the right way to use `header('Content-Type: text/plain');`. I've tried it but did not get the output that I wanted. –  Nov 01 '20 at 07:15
  • The way I wrote it is the way you use it. It must appear before any other output. If that doesn't work, share more information. – Evert Nov 01 '20 at 07:19
-1

You are rendering it in a browser without any HTML formatting. Wrapping it in a <pre></pre> tags will preserve its plaintext formatting (newlines and whitespace) when rendered in the browser.

<pre>
<?php
echo "Hello
World
Foo Bar!";
</pre>


$aString = '
First Line
Second Line
Third Line';

<pre>
echo $aString;
</pre>
?>
jpmc
  • 1,147
  • 7
  • 18