What are some best practices for using PHP to generate and manipulate HTML files with user input?

When generating and manipulating HTML files with user input in PHP, it is important to properly sanitize and validate the input to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. It is also recommended to separate the PHP logic from the HTML presentation by using templates or frameworks to maintain clean and maintainable code. Additionally, consider using PHP functions like htmlspecialchars() to escape user input before outputting it to the HTML file.

<?php
// Sanitize and validate user input
$user_input = $_POST['user_input'];
$clean_input = htmlspecialchars(strip_tags($user_input));

// Generate HTML file with user input
$html = "<html><head><title>User Input</title></head><body>";
$html .= "<h1>User Input:</h1>";
$html .= "<p>" . $clean_input . "</p>";
$html .= "</body></html>";

// Save HTML file
file_put_contents('user_input.html', $html);
?>