Why does PHP echo'd text lose its formatting?

2020-01-26 10:17发布

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

7条回答
爷的心禁止访问
2楼-- · 2020-01-26 10:48

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.

查看更多
Lonely孤独者°
3楼-- · 2020-01-26 10:57

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>

查看更多
一纸荒年 Trace。
4楼-- · 2020-01-26 10:57

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

查看更多
Summer. ? 凉城
5楼-- · 2020-01-26 11:01

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.

查看更多
smile是对你的礼貌
6楼-- · 2020-01-26 11:02

You could try add nl2br() function...

something like this: echo nl2br($your_text_variable);

It should work ;-)

查看更多
Animai°情兽
7楼-- · 2020-01-26 11:04

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:

查看更多
登录 后发表回答