\n and \r\n not escapping when they are printed in the browser

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 .

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

2 Answers

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

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like