What role does htmlentities() play in preventing special character encoding issues in PHP applications?

Special characters can cause encoding issues in PHP applications, leading to security vulnerabilities like cross-site scripting (XSS) attacks. The htmlentities() function in PHP helps prevent these issues by converting special characters to their HTML entities, ensuring that they are displayed as text rather than interpreted as code by the browser.

<?php
$unsafe_input = '<script>alert("XSS attack!")</script>';
$safe_input = htmlentities($unsafe_input);
echo $safe_input;
?>