What role does htmlspecialchars() play in preventing XSS attacks when displaying data in PHP applications?

XSS attacks occur when user input is not properly sanitized before being displayed on a webpage, allowing malicious scripts to be executed. The htmlspecialchars() function in PHP converts special characters like < and > into their HTML entities, preventing these characters from being interpreted as HTML or JavaScript code. By using htmlspecialchars() to sanitize user input before displaying it on a webpage, you can help prevent XSS attacks in PHP applications.

$user_input = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;)&lt;/script&gt;&quot;;
$clean_input = htmlspecialchars($user_input);
echo $clean_input;