Saswat Saswat - 19 days ago 6
PHP Question

How to display text saved in DB, properly in HTML?

I am creating an application using PHP and MySQL.

In the DB, the data is saved in the following manner:

DB-Data

But, while displaying the result in HTML page, the result comes like this:

HTML display

The issue might be because HTML needs tags like

"<br/>"
, etc......

How can I display the result in actual format?

Here's the code section displaying the data:

<div class="com-text">
<?php echo $row['chatDesc'];?>
</div>


EDIT:



Also, I need to display the data by creating a div using jquery(dynamically). So how to display it in javascript format too?

html += '<div class="com-text">'+data.chat[i].chatDesc+'</div>';
$("#chat_list").append(html);

Answer

You should use nl2br which inserts line breaks where newlines occur in a string

the javascript equivement of this function + your code:

function nl2br (str, is_xhtml) {   
  var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : 

  '<br>';    
  return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

html += '<div class="com-text">'+nl2br(data.chat[i].chatDesc, true)+'</div>';
$("#chat_list").append(html);