What are the best practices for preserving formatting, including line breaks and special characters, when retrieving data from a database in PHP?

When retrieving data from a database in PHP, it's important to preserve formatting such as line breaks and special characters. To achieve this, you can use the nl2br() function to convert newlines to HTML line breaks and htmlspecialchars() function to encode special characters. This ensures that the data is displayed correctly on the web page without any formatting issues.

// Retrieve data from the database
$data = $row['content'];

// Preserve formatting
$formatted_data = nl2br(htmlspecialchars($data));

// Display the formatted data
echo $formatted_data;