I am trying to display a block of text which contains whitespace, new line etc. which is retrieved from the MySQL database. The data is saved in the DB with newline. but when it is displayed in the php page new lines are not shown. All text comes in one single line. Please help. Thanks in advance.
The code which displays the block of text from db:
<?php if (isset($row['Description'])) {?>
<p>Description :</p> <?=$row['Description'] ?>
<?php } ?>
If Description is saved in DB as :
"First line text
Second line text
Third line text."
It is displayed in the web page as:
"First line text Second line text Third line text."
I want the result as :
"First line text
Second line text
Third line text."
-
3Please use the search before asking a question. Really. I mean sometimes I ask myself stupid questions, too, but actually I search before I post them here. -- Please see: How can I use CSS to preserve line breaks in an HTML <code> block?hakre– hakre2012年12月28日 18:04:45 +00:00Commented Dec 28, 2012 at 18:04
3 Answers 3
PHP nl2br() function is your friend!
<?php
if (isset($row['Description']))
{
echo '<p>Description :</p>';
echo nl2br($row['Description']);
}
?>
Comments
Use nl2br():
<?php if (isset($row['Description'])) {?>
<p>Description :</p> <?=nl2br($row['Description']); ?>
<?php } ?>
Comments
Your problem is that HTML automatically collapses whitespace characters. You need to actually output a <br> tag in HTML to force a new line.
To this end, you have the nl2br() function which you can run your database out through to convert newline characters to <br> tags.
So use it like this:
echo nl2br($your_database_content);