Roger
Roger

Reputation: 6527

Why does PHP echo'd text lose its formatting?

Any ideas why formatted text from DB, when echo-ed out in php loses its formatting, i.e. no new lines? Thanks!

enter image description here

Upvotes: 10

Views: 13450

Answers (7)

OsowoIAM
OsowoIAM

Reputation: 77

This should be helpful in answering. How do I keep whitespace formatting using PHP/HTML?enter link description here

Set up a string preprocessing code for both input to database and output to display page

Upvotes: 0

daGrevis
daGrevis

Reputation: 21333

Use nl2br().

New lines are ignored by browser. That's why you see all text without line breaks. nl2br() converts new lines to <br /> tags that are displayed as new lines in browsers.

If you want to display your text in <textarea>, you don't need to convert all new lines to <br />. Anyway, if you do it... you will see "<br />"s as text in new lines places.

Upvotes: 30

takeshin
takeshin

Reputation: 50638

The reason

This is the default behavior for all user agents. If you look at the page source, you'll see that your text has the same formatting like the one in the database (or textarea).

The reason of your confusion is probably that you once see the text in the <textarea> tag, which displays preformatted text, does not interpret the tags, and in the other case the text is interpreted (whitespace is not important in this case).

The browsers don't display new lines, unless specifically asked for - using <br> tag or any block level tags.

No tags == no new lines.

The fix

If you store preformatted text in the database,
you should wrap the output in the <pre> tag.

You may want to convert the formatting characters to the HTML tags you need using set of functions like nl2br, str_replace etc.

You may also correct your structure to store the HTML in the database instead of just plain text (however markup looks like a better solution).

See similar question:

Upvotes: 8

radzio
radzio

Reputation: 2892

You could try add nl2br() function...

something like this: echo nl2br($your_text_variable);

It should work ;-)

Upvotes: 9

hakre
hakre

Reputation: 197767

It does output what you say to output. If the text is pre-formatted, put it inside the HTML <pre></pre> tag in your output script.

Upvotes: 2

sdolgy
sdolgy

Reputation: 7001

The difference between the two images you show is that one has the text in a <textarea></textarea> and the other does not ... if you want 1:1: <textarea><?php echo $yourVariable;?></textarea>

Upvotes: 3

Tobias
Tobias

Reputation: 7380

Because there are no html tags for formatting! Try the nl2br function.

Upvotes: 14

Related Questions