Why does PHP echo'd text lose its formatting?

前端 未结 7 1729
南旧
南旧 2020-11-27 21:39

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

\

相关标签:
7条回答
  • 2020-11-27 22:18

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

    0 讨论(0)
  • 2020-11-27 22:19

    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>

    0 讨论(0)
  • 2020-11-27 22:21

    You could try add nl2br() function...

    something like this: echo nl2br($your_text_variable);

    It should work ;-)

    0 讨论(0)
  • 2020-11-27 22:22

    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.

    0 讨论(0)
  • 2020-11-27 22:22

    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.

    0 讨论(0)
  • 2020-11-27 22:26

    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:

    • How do I keep whitespace formatting using PHP/HTML?
    0 讨论(0)
提交回复
热议问题