How can one ensure that HTML code retrieved from a database is displayed correctly in PHP?

When HTML code is retrieved from a database in PHP, it may not display correctly due to special characters like "<" and ">". To ensure proper display, you can use the htmlspecialchars() function in PHP to convert these characters into their HTML entities. This will prevent the browser from interpreting them as HTML tags and display the content as intended.

&lt;?php
// Retrieve HTML code from database
$html_code = &quot;&lt;p&gt;Hello, &lt;strong&gt;world&lt;/strong&gt;!&lt;/p&gt;&quot;;

// Display HTML code with htmlspecialchars
echo htmlspecialchars($html_code);
?&gt;