How can the htmlspecialchars function in PHP be utilized to ensure proper display of HTML content in different contexts?
When displaying user-generated content on a webpage, it is important to properly escape special characters to prevent XSS attacks and ensure the content is displayed correctly. The htmlspecialchars function in PHP can be used to convert special characters like < and > into their HTML entities, ensuring that the content is displayed as intended without executing any malicious code.
$user_input = "<script>alert('XSS attack!')</script>";
$escaped_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $escaped_input;