What is the correct way to format and output data from a database in PHP to ensure valid HTML code?

When outputting data from a database in PHP to ensure valid HTML code, you should use htmlspecialchars() function to escape special characters in the data. This will prevent any potential security vulnerabilities such as cross-site scripting attacks. By using htmlspecialchars(), you can safely output the data without affecting the HTML structure.

<?php
// Assuming $data is the variable containing the data fetched from the database
echo htmlspecialchars($data);
?>