How can you get the line breaks to work when you retrieve data from MySQL to PHP?

In most raw (not formatted) text, such as the text in a simple HTML input element, new lines are denoted by a special "newline" character (commonly referred to as \n). When the text reaches this character, it pulls the text following it to the next line.

For example, the string "hello\nworld" would actually appear as:

hello

world

When you submit and retrieve text data in MySQL, it preserves these newline characters as they were originally entered. When you print them onto an HTML page, you may notice that newline characters do not seem to "work" as you could expect them to. The previous string would actually appear as "helloworld", instead of being broken up into two lines.

This is because the string is printed into the HTML source code as "hello\nworld". Browsers are supposed to ignore most whitespace and newlines, which would give us the resulting "helloworld".

In HTML, new lines are created with the <br /> element. When pulling raw text data from MySQL, you will probably want to replace any occurrences of newline characters (which is the raw text's way of creating new lines) with the <br /> element (which is HTML's).

A function exists which easily makes the replacements. It is the nl2br() function, which (simply put) accepts one string as an argument (the text data to replace newline characters) and returns a string (the text data with \n replaced as <br />).

Example:

<?php

$string_taken_from_mysql = 'hello \n\n hello';

echo nl2br($string_taken_from_mysql);

?>

Outputs:

hello

hello