How to add a line break within echo in PHP?

Php

Php Problem Overview


I was trying to add a line break for a sentence, and I added /n in following code.

echo "Thanks for your email. /n  Your orders details are below:".PHP_EOL;
echo 'Thanks for your email. /n  Your orders details are below:'.PHP_EOL;

For some reasons, the I got server error as the result. How do I fix it?

Php Solutions


Solution 1 - Php

\n is a line break. /n is not.


use of \n with

1. echo directly to page

Now if you are trying to echo string to the page:

echo  "kings \n garden";

output will be:

kings garden

you won't get garden in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n. You need to use the nl2br() function for that.

What it does is:

>Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

echo  nl2br ("kings \n garden");

Output

kings
garden

> Note Make sure you're echoing/printing \n in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is

so "\n" not '\n'

2. write to text file

Now if you echo to text file you can use just \n and it will echo to a new line, like:

$myfile = fopen("test.txt", "w+")  ;

$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
 

output will be:

kings
 garden

Solution 2 - Php

You have to use br when using echo , like this :

echo "Thanks for your email" ."<br>". "Your orders details are below:"

and it will work properly

Solution 3 - Php

The new line character is \n, like so:

echo __("Thanks for your email.\n<br />\n<br />Your order's details are below:", 'jigoshop');

Solution 4 - Php

You may want to try \r\n for carriage return / line feed

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjumaxView Question on Stackoverflow
Solution 1 - PhpNullPoiиteяView Answer on Stackoverflow
Solution 2 - PhpMaryam HomayouniView Answer on Stackoverflow
Solution 3 - PhpnoetixView Answer on Stackoverflow
Solution 4 - PhpJonathanView Answer on Stackoverflow