-2

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."
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
user1353083
  • 59
  • 1
  • 1
  • 3
  • 3
    Please 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 block?](http://stackoverflow.com/questions/1011641/how-can-i-use-css-to-preserve-line-breaks-in-an-html-code-block) – hakre Dec 28 '12 at 18:04

3 Answers3

12

PHP nl2br() function is your friend!

<?php 
if (isset($row['Description'])) 
{
    echo '<p>Description :</p>';
    echo nl2br($row['Description']);
} 
?>
Ray Paseur
  • 2,106
  • 2
  • 13
  • 18
3

Use nl2br():

<?php if (isset($row['Description'])) {?>
<p>Description :</p> <?=nl2br($row['Description']); ?>
<?php } ?>
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

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);
Mike Brant
  • 70,514
  • 10
  • 99
  • 103