The difference between \n and <br /> in php [duplicate] - php

This question already has answers here:
\n vs. PHP_EOL vs. <br>?
(7 answers)
Closed 8 years ago.
I was studying php with tutorial. I recognized that in php is sometimes use like this
echo $myString."<br />"
Suddenly, there came another in the tutorial "\n" and I got confused. Can I use it just like I use
<br />
?
So like this?
echo $mySting."\n"
Is it like a html tag?
What's the difference between
<br /> and \n?

<br /> is a HTML line-break, whereas \n is a newline character in the source code.
In other words, <br /> will make a new line when you view the page as rendered HTML, whereas \n will make a new line when you view the source code.
Alternatively, if you're outputting to a console rather than somewhere that will be rendered by a web browser then \n will create a newline in the console output.

\n is a new line feed within the context of plain text, while <br /> is line break within the context of HTML.
HTML can interpret \n when using preformatted blocks (e.g. <pre>), but it does not by default, and should not unless there is a specific use case (like when quoting, citing poetry, or showing code).
<br /> should never be used to separate text that should otherwise be treated as a paragraph, heading or other group of text.

\n is a new line character (a literal new line as you would type in your code).
$newline = "
";
var_dump($newline === "\n");
// true
You can also use the PHP constant PHP_EOL (end of line). Note, that '\n' will render \n as a literal string; you must use double quotes to have it rendered as a new line character. Also note, that my above example may actually output false..since sometimes new lines are rendered as \r\n.
<br /> is an HTML element for a line break. This will show up as a new line when HTML is rendered in a browser.
The only time that \n will show up as a rendered line break in HTML, is when it is within a <pre> (pre-formatted text) element. Otherwise it would be the same as just formatting/indenting your HTML code:
<?php
echo "<html>\n\t<body>\n\t\tHello World!\n\t</body>\n</html>";
Outputs:
<html>
<body>
Hello World!
</body>
</html>

Related

How to show line break using PHP?

I am inserting this text What is <br/> PHP? into the database
Now I want to show this text as a line break. Like below:
What is PHP?
I am using PHP nl2br() function but it's not working. I am getting the value like this:
What is <br/> PHP?
How can I solve it?
Thank You.
A question comes up here... where are you inserting this text (string) ?
If you are injecting it as HTML you'll get the desired result in the rendered page.
I assume this is not the case: you want HTML line breaks turned into newlines.
So...
nl2br()converts newlines into <br />: that's the opposite you want to do
http://php.net/manual/en/function.nl2br.php
Just use str_replace:
$out = str_replace( "<br/>", "\n", $in );
Where $in is the input string and $out is the desired output
http://php.net/manual/en/function.str-replace.php
Just a couple of things to note:
1) the above code will work with HTML line breaks <br/>, not if you have <br>, or <br />
If this is an issue you may pass the function array of strings and array of their replacements. This is well documented in the link above.
2) If you use the code snipped I wrote above you'll end having two spaces in the resulting string:
What is  (with trailing space)
 PHP (with leading space)
Just use css instead of server-side transformations:
p {
white-space: pre-line;
}
<p>I am inserting this text What is
PHP? into the database
</p>
<p>Now I want to show this text as a line break. Like below:</p>
<p>What is
PHP?</p>

PHP: Character escaping not working with double quotes unless there is a <pre> tag?

Please can someone tell me where I'm going wrong?
//outputs : Hi, my name is Jackal I like PHP
<?php
echo "Hi, my name is Jackal \nI like PHP";
?>
Whereas if I use pre tag
//outputs: Hi, my name is Jackal
// I like PHP
<pre>
<?php
echo "Hi, my name is Jackal \nI like PHP";
?>
Can someone please explain why character escaping isn't working?
thanks
PHP is interpreting that line break. Look in the source code of the webpage. You'll see that you have 2 lines in the source.
However, HTML handles line breaks differently. To perform a line break in HTML, use the <br> tag. This will make the HTML output over 2 lines on the webpage itself. However, in the source code, it will still appear as a single line (unless you add that line break).
What <pre> is doing is telling the HTML engine to output the exact string as-is since the text is preformatted, including interpreting that line break. Also note, you should add a closing </pre> tag at the end of the block that is preformatted.
If you have this in your HTML:
<p>Hello,
World!</p>
Does it appear on one line, or two?
Usually, the answer is one: whitespace is condensed into a single space.
<pre>, however, has the default CSS of white-space:pre, which does NOT condense whitespace.
You should echo "<br />", or apply white-space:pre (or, even better, white-space:pre-wrap) to the container element.
Because in your browser \n shows just a whitespace and does not appear as line break unless you use pre-formatted HTML tag <pre>.
e.g. following will display with a line break in browser:
echo "Hi, my name is Jackal <br />I like PHP";
or this one also:
echo "<pre>Hi, my name is Jackal \nI like PHP</pre>";
As you can make out that <pre> tag is for displaying pre-formatted text hence \n does show as line break.
Character escaping is working. Look at the source code, there you'll find the new line. In order to make it visible in a browser you need an html tag (<br />) or the wrapping <pre>
<br>
is HTML.
<br />
is XHTML (recommended).
\n
is a newline in the code (works while writing to file, but doesn't output to the screen).
alternately you can use nl2br as below
echo nl2br("Hi, my name is Jackal \nI like PHP");
The newline character in php actually echos a new line itself.
However, the output of php's echo statement is still the source code of the web browser. Hence, the browser condenses all the extra line breaks and spaces. For example:
<p>Hello
there</p>
outputs
Hello there
despite the white space. To get around this issue, use the <br>/<br/> tag to tell the browser to make a newline, instead of tell php to make a newline.

PHP won't output new line [duplicate]

This question already has answers here:
PHP - how to create a newline character?
(15 answers)
Closed 9 years ago.
I've tried every method to output a newline in PHP. Why doesn't the following work? :
<?php
$foo = 'bar';
echo "Hello \n $foo!";
?>
This should output a newline between hello and bar but it isn't.
I also tried \r\n instead of \n
If you using it as command line script this would work. I would use PHP_EOL for this since it chooses the right line break for the OS.
However if you are working with HTML (viewing the result in browser for example) you have to use the HTML way of linebreaks which is: <br />
To output a new line in HTML you need to use HTML's representation of a new line which is <br/>
php has a function for you that converts all natural new lines to HTML new lines > nl2br()
Then your code should look like
<?php
$foo = 'bar';
echo nl2br("Hello \n $foo!");
?>
Use <br> when inserting line break in html
To output a new line visually (in a browser), you need HTML:
echo "Hello\n<br />$foo!";
\n is a system line feed.
Try this:
<?php
$foo = 'bar';
echo "Hello <br> $foo!";,
?>
if you view the source you will see it actually DOES have a new line in it, But white space doesnt matter in HTML (what the browser displaying the output is expecting) but adding a <br /> to your statement will produce a new line because this is the way browsers read new lines and display them.

New line ("\n") in PHP is not working

For some strange reason, inserting echo "\n"; and other scape sequence characters are not working for me, that's why I am just using <br /> instead.
The images of the results of examples in books and other documentations seems just alright. I'm currently using XAMPP and already used WAMPP with the same actual result. Why is that?
Edit:
It seems that I cannot understand the concept after comparing your answers with this:
PHP Linefeeds (\n) Not Working
Edit:
Sorry I didn't realized that the link above is referring to a php code writing to a file. I just wonder why I have these few php sample programs that uses \n even though it outputs in a webpage. Thanks everyone.
When you run a PHP script in a browser, it will be rendered as HTML by default. If the books you’re using show otherwise, then either the code or the illustration is inaccurate. You can use “view source” to view what was sent to the browser and you’ll see that your line feeds are present.
<?php
echo "Line 1\nLine 2";
?>
This will render in your browser as:
Line 1 Line 2
If you need to send plain text to your browser, you can use something like:
<?php
header('Content-type: text/plain');
echo "Line 1\nLine 2";
?>
This will output:
Line 1
Line 2
PHP Linefeeds (\n) Not Working is referring to sending output to a file rather than the browser.
You should be looking for nl2br(). This will add line breaks (<br>) to your output which will be rendered by the browser; newlines are not.
The echo "\n" is probably working, just not the way you expect it to.
That command will insert a new line character. From the sounds of it, you're using a browser to view your output. Note that if you wrote an HTML file that had a body contents that looked like:
<p>This
is
a
test </p>
The browser rendering would not include the new lines, and would instead just show "This is a test"
If you want to see the newlines, you could view source, and you'll see that the source code includes the new lines.
The rule of thumb is that if you need new lines in a browser, you need to use HTML (e.g. <br />), while if you want it in plain text, you can use the \n
<br /> is the HTML Tag for new line, whereas
"\n" is to output a new line (for real).
The browser doesn't output a new line each time the HTML file goes to the next line.
You can use the nl2br function to convert \n to <br>
As said before, HTML does not render \n as new line. It only recognizes the <br> html tag
If you are working with HTML (viewing the result in browser for example) you have to use the HTML way of linebreaks which is: <br>
/n only works if it is used as a simple text but here as we code in a html doc it takes it as a HTML text hence you can use </br> tag instead.
PHP outputs on the browser and browser only render output in HTML, any other output format will be ignored by the browser.
If you want browser to keep your standard output format as it is, you should enclose your output under HTML's <pre> tag. It preserves the formatting:
echo "<pre>";
echo "This is first line\nThis is new line";
echo "</pre>";
This will be rendered as
This is first line
This is new line
Alternatively, you can mention content type to be plain text in the header:
header('Content-type: text/plain');
echo "This is first line\nThis is new line";
This will tell the browser to render the output as plain text. And the browser will encolse the output automatically in <pre> tag.
solution is echo nl2br or=> <br>

What good is new line character?

I don't really get it: what's the purpose of a new line character?
If I do this:
<?php
echo "This is a test. \n";
echo "This is another test.";
?>
Code results in both sentences being in the same line. Why doesn't the \n causes the second sentence being in second line?
The sentences are each in it's own line, if I do:
<?php
echo "This is a test. <br>";
echo "This is another test.";
?>
But I have also seen people do this:
<?php
echo "This is a test. <br>\n";
echo "This is another test.";
?>
Which essentially results in the same output as the second code snippet. Someone care to explain this?
The HTML standard treats a line break as just another white space character, which is why the <br> tag exists. Note however a line break will work within a <pre> tag, or an element with the white-space:pre CSS style.
The third example is just to make "pretty" HTML: it makes it easier to "view source" and check it by eye. Otherwise, you have a big long string of HTML.
as you have observed there are different ways to create a new line.
<br />
this is not a new line character, this is an XHTML tag which means, it works in XHTML.
correctly speaking it is not a new line character but the tag makes sure, one is inserted = it forces a line break. closing tag is mandatory.
XHTML specs
<br>
this is a HTML tag which forces a line break. closing tag is prohibited.
HTML 4.1 specs
\n
is an escape sequence for the ASCII new line char LF. A common problem is the use of '\n' when communicating using an Internet protocol that mandates the use of ASCII CR+LF for ending lines. Writing '\n' to a text mode stream works correctly on Windows systems, but produces only LF on Unix, and something completely different on more exotic systems. Using "\r\n" in binary mode is slightly better, as it works on many ASCII-compatible systems, but still fails in the general case. One approach is to use binary mode and specify the numeric values of the control sequence directly, "\x0D\x0A".
read more
PHP_EOL
is a php new line constant which is replaced by the correct system dependent new line.
so the message is, use everything in it's right place.
<br> will give you a new line in the user's view; \n will give you a new line in source code, ie. developer's view.
When the html is rendered, only the "<br />" renders the break line. However the markup is much easier to read when "<br />\n" is printed, so that everything is not in one long line.
\n is code based
<br /> is HTML tag based
There is a clear distinction between the two.
Your problem is the way html is rendered. If you look in the source code, the first example will have the two lines on separate lines, but the browser does not see line breaks as breaks that should be displayed. This allows you to have a long paragraph in your source:
rghruio grgo rhgior hiorghrg hg rgui
ghergh ugi rguihg rug hughuigharug
hruauruig huilugil guiui rui ghruf hf
uhrguihgui rhguibuihfioefhw8u
beruvbweuilweru gwui rgior
That would only wrap as the browser needed it to, allowing it to be easily editable at the right line length, but displayed at any resolution.
HTML does not care about new lines in the source code, you can put it all in one line. It will only interpret <br /> as a new line. You should use an \n to beautify your HTML-output though, but the better way is to not output it with PHP, but to use it in the HTML itself and only embed PHP stuff into it, like this:
<ul id="menu">
<?php foreach ($menu_items as $item): ?>
<li>
<a href="<?= htmlspecialchars($item['link']) ?>" title="<?= htmlspecialchars($item['title']) ?>">
<?= htmlspecialchars($item['title']) ?>
</a>
</li>
<?php endforeach; ?>
</ul>
That way you won't have to bother with formatting inside PHP, but you automagically have it, by design, in HTML. Also, you seperate Model-logic and View-logic from each other like this and leave the output to your HTTP Server rather than the PHP engine.
That's because you're creating HTML and view it in a browser, and whitespace is more or less ignored there. Ten spaces don't produce a bigger gap than one space, but that doesn't mean that the space character doesn't work. Try setting the content type to text/plain or look at the HTMLs source to see the effect of the newline.
The correct XHTML syntax for it would be
echo "This is the test code <br />\n";
The <br /> renders a new line onscreen, the "\n" renders a new line in the source coed
The new line character is useful otherwise, such as in a PDF. You're correct that the new line character has very little do with HTML as other people have said, it's treated as another while space character. Although it is useful inside the <pre> tag. It can also be used to format the HTML output to make it easier to read. (It's a little annoying to try to find a piece of HTML in a string that's 1000 characters wide.)
The new line character is also useful when storing data in the database. Usually you want to store the data without HTML special characters such as <br /> so that it can be easily used in other formats (again, such as PDF). On output, you want to use the nl2br() function to convert the new lines to <br />s.
The new line character is is useful for string functions.
For example:
explode( '\n' , $input );
Would split a string by a new line.
str_replace( '\n' , '<br />' , $input );
Would replace every newline in $input with a br tag.
Also because PHP also has a CLI, \n is useful for formatting:
eg.
echo 'Hello world';
Would, in the CLI, output;
Hello worldphp>
echo 'Hello world' . "\n";
would output;
Hello world
php>
Although it also has uses when writing web-based scripts, keep in mind PHP is more than a web engine; it also has a CLI where the br tag is useless.
<br /> is also useless if you're running a script from the command line.
$ php -f file.php
Output <br />$
I know not too many people use PHP from the command line, but it does come up:
file.php:
<?php
print "Output\n";
?>
At the command line:
$ php -f file.php
Output
$

Categories