开发者

how to show the content exactly as it's saved in mysql

开发者 https://www.devze.com 2023-01-08 00:04 出处:网络
i have a content stored in mysql like below: first line second line third line but when i use the echo function it shows the output like this

i have a content stored in mysql like below:

first line
second line
third line

but when i use the echo function it shows the output like this

first line second li开发者_开发知识库ne third line

however i want to show the output exactly as its saved in mysql.


You are outputing it exactly as MySQL stores it. The browser is set to display it differently than you output it because you're outputting text content to an HTML page. (In particular, it doesn't display a newline for each newline you output).

To get it to display in HTML correctly, you need to replace the newlines with a line break character, nl2br is a useful function for this exact purpose.

Other ways to force the browser to display it as you intend is to set the content type as text/plain instead of text/html or use the <pre> tag.


echo nl2br($str_from_db);


In this particular case, you can replace \n on your string with <br> tags.

From PHP manual on str_replace:

$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n"; // THIS IS YOUR DB VALUE!
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';
// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);

You are viewing it like that because \n (new lines) don't have the new line effect on HTML. They just show one next to the other. To force a line break you need to use a <br/> tag or a table, or a unordered line...


You can wrap the content in <pre></pre> or <code></code> tags or specify CSS properties for the element that you're using to display the content from MySQL.

For example:

CSS:

.mysql-content {
    white-space: pre;
}

HTML:

<div class='mysql-content'>first line
second line
third line</div>

Should display the way you want it to.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号