In what sequence should text manipulation, database storage, and HTML output be performed to ensure proper rendering of div tags and encoded characters in PHP?

When working with div tags and encoded characters in PHP, it is important to follow a specific sequence to ensure proper rendering. First, any text manipulation or encoding should be done on the data before storing it in the database. Next, the data should be stored in the database as is, without any further manipulation. Finally, when retrieving the data from the database, it should be properly encoded and formatted for HTML output, including wrapping it in appropriate div tags.

// Text manipulation and encoding
$data = htmlspecialchars($data);

// Database storage
// Assuming $data is stored in the database here

// HTML output
echo '<div>' . $data . '</div>';