How can PHP automatically escape special characters in HTML code?

When outputting user-generated content in HTML using PHP, it's important to escape special characters to prevent potential security vulnerabilities like cross-site scripting (XSS) attacks. PHP provides the `htmlspecialchars()` function, which automatically converts special characters like <, >, ", ', and & into their HTML entity equivalents, ensuring that the content is safely displayed in the browser.

&lt;?php
$userInput = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;)&lt;/script&gt;&quot;;
echo htmlspecialchars($userInput, ENT_QUOTES);
?&gt;