What role does the nl2br function play in preserving formatting when retrieving text from a database in PHP?

When retrieving text from a database in PHP, the nl2br function is used to preserve line breaks and formatting that may have been stored in the database. This function converts new line characters (\n) into HTML line breaks (<br>) so that the text displays correctly in a web browser.

// Retrieve text from database
$text = &quot;This is a text with\nline breaks.&quot;;

// Preserve formatting using nl2br
$formattedText = nl2br($text);

// Display the formatted text
echo $formattedText;