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 = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;)&lt;/script&gt;&quot;;
$escaped_input = htmlspecialchars($user_input, ENT_QUOTES, &#039;UTF-8&#039;);
echo $escaped_input;