Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a line break within echo in PHP? [closed]

Tags:

php

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?

like image 427
jumax Avatar asked Oct 21 '12 03:10

jumax


1 Answers

\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 
like image 127
NullPoiиteя Avatar answered Sep 28 '22 03:09

NullPoiиteя