What are some best practices for outputting formatted text from a database using PHP?

When outputting formatted text from a database using PHP, it's important to properly sanitize the data to prevent SQL injection attacks and to format the text as needed for display. One common approach is to use PHP's htmlentities function to convert special characters to HTML entities, which helps prevent XSS attacks and ensures proper rendering of the text.

// Assuming $row['text'] contains the text retrieved from the database
$formattedText = htmlentities($row['text']);
echo "<p>{$formattedText}</p>";