What best practices should PHP developers follow when outputting HTML to avoid security vulnerabilities and ensure valid markup?

When outputting HTML in PHP, developers should always sanitize user input to prevent cross-site scripting (XSS) attacks. This can be done using functions like htmlspecialchars() to escape special characters. Additionally, developers should ensure that the generated HTML markup is valid by using proper tags and attributes.

<?php
// Sanitize user input before outputting to prevent XSS attacks
$user_input = "<script>alert('XSS attack');</script>";
$sanitized_input = htmlspecialchars($user_input);

// Output the sanitized input in valid HTML markup
echo "<p>" . $sanitized_input . "</p>";
?>