Any ideas why formatted text from DB, when echo-ed out in php loses its formatting, i.e. no new lines? Thanks!
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
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.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>
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
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.You could try add
nl2br()
function...something like this:
echo nl2br($your_text_variable);
It should work ;-)
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: