How can PHP code be used to maintain formatting when retrieving data from a MySQL database for display on a webpage?

When retrieving data from a MySQL database to display on a webpage using PHP, you can maintain formatting by using the PHP `nl2br()` function. This function converts new line characters (\n) to HTML line breaks (<br>) so that the text appears correctly formatted on the webpage.

&lt;?php
// Retrieve data from MySQL database
$data = &quot;This is a text with \n new line characters.&quot;;

// Display data on webpage with formatting maintained
echo nl2br($data);
?&gt;