How can the nl2br function be used to preserve line breaks in PHP when retrieving data from a database?

When retrieving data from a database in PHP, line breaks are often stored as "\n" or "\r\n". When displaying this data on a webpage, these line breaks may not be rendered correctly. To preserve line breaks, you can use the nl2br function in PHP, which converts newline characters to HTML line breaks (<br>). Simply apply the nl2br function to the retrieved data before displaying it on the webpage.

// Retrieve data from the database
$data = &quot;Hello\nWorld&quot;;

// Preserve line breaks using nl2br
$preserved_data = nl2br($data);

// Display the preserved data on the webpage
echo $preserved_data;