drenl
drenl

Reputation: 1333

php Newlines vs html break

This code:

<?php
  echo "This is the first line. \n";
  echo "This is the second line.";
?>

Echoes out all on the same line: ("This is the first line. This is the second line.")

Shouldn't \n have basically the same function as <br> ? What am I missing here?

Upvotes: 1

Views: 79

Answers (4)

Seth McClaine
Seth McClaine

Reputation: 10040

HTML doesn't render \n, a \n will put a break in your HTML source code

PHP

<?php
echo "<p>This is the first line. \n";
echo "This is the second line.</p>";
?>

HTML Source

<p> This is the first line.
This is the second line.</p>

HTML

This is the first line. This is the second line.

PHP

<?php
echo "<p>This is the first line.";
echo "This is the second line.</p>";
?>

HTML Source

<p> This is the first line.This is the second line.</p>

HTML

This is the first line.This is the second line.

PHP

<?php
echo "<p>This is the first line. <br/>";
echo "This is the second line.</p>";
?>

HTML Source

<p> This is the first line.<br/>This is the second line.</p>

HTML

This is the first line. 
This is the second line.

Upvotes: 5

RiaD
RiaD

Reputation: 47658

You mix up the output of php and the result in your browser. \n is newline. You may see it, when you read the source code in your browser(Ctrl + U in Chrome) .

But browser only render <br> as newline on webpage

Upvotes: 3

OptimusCrime
OptimusCrime

Reputation: 14863

echo "This is the first line. \n";

Will produce a linebreak in your source, meaning the cursor is currently on the next line (the line belove the text).

echo "This is the second line.";

Will produce a single line and leave the cursor right after the text (on the same line).

echo "This is the second line.<br />";

Will produce a single line but in rendered html containing a visible linebreak. However, in the sourcecode there will be no linebreaks, so:

echo "Line one<br />Line two";

Will render two lines in html but one line in the source.

Upvotes: 2

CodeAngry
CodeAngry

Reputation: 12995

echo "This is the first line.", '<br />', PHP_EOL;

^ HTML code for BR and ENTER.
ENTER is visible in the source or PRE tags, or TEXTAREAs, or when enabled by CSS white-space (etc.) while BR is the line break in HTML.

Upvotes: 1

Related Questions