-1

I am not sure if this is an Ubuntu, Apache or PHP issue.

The following basic scripts do not render a new line in my Firefox browser.

  1. echo "this is not \n creating a new line";
  2. echo "this is not \r\n creating a new line";
  3. echo "this is not creating a new line";

I am currently learning PHP and have no idea where to even start solving this. All I know from Googling is that the above 3 should work.

This works

  1. echo "this does <br> create a new line";

My setup:

Ubuntu 18.04.2
Apache/ 2.4.29 (ubuntu)
PHP 7.3.7-2+ubuntu18.04.1
Fireforx Developer (Quantum) 68.0.1 (64bit)

Thank you @cmak.fr and @Mathieu for your answers. It makes better sense now. I also found this link after reading you reply https://www.webmasterworld.com/php/3127164.htm.

Snooping bit further I found that the <pre> tag also works when combined with \n. Why is that?

<html>
   <body>
     <h1>Some h1</h1>
     <p>Some text</p>
     <pre>
      <?php
        echo "this is not \n creating a new line";?>
     </pre>
   </body>
</html>
  • 2
    Browsers render new lines as whitespaces. And they render multiple successive whitespaces as a single whitespace. If you want to show have a new line, you need to use HTML. Replace the \n with <br /> for it to work or encapsulate your code with the <pre></pre> tags. I recommend you learn some HTML first if you're starting into web development while learning PHP. Meanwhile, I am voting to close this question as general coding questions are usually offtopic on Ask Ubuntu. – Dan Aug 7 '19 at 8:32
  • @Dan I don't see general coding questions defined as off topic in the help center. askubuntu.com/help/on-topic – mchid Aug 8 '19 at 12:32
1

A new line inside the html source code is not displayed as a newline in a browser.
Take a look at the source code of your generated html pages, you will find your newlines

The html code of a new line is <br>

In short

<?php echo "\r\n"; ?> // Writes a new line in the output stream
<?php echo "<br>"; ?> // Writes the newline html code

Another example:

<php
echo "<html><body>A<br>\r\nB<br>C\r\n</body></html>"
?>

Will output the raw text:

<html><body>A<br>
B<br>C
</body></html>

A browser will display this

A
B
C
0

AFAIK, lines break are made with <br> or <br /> tags.

You can convert \n to <br /> with nl2br function:

<?php
    $line = "First line\nSecond line."
    echo nl2br($line);
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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