How can the use of htmlspecialchars() function in PHP help prevent XSS attacks and improve data sanitization in web applications?

XSS attacks occur when a malicious user injects scripts into a web application, leading to the execution of unauthorized code on the client side. The use of the htmlspecialchars() function in PHP helps prevent XSS attacks by converting special characters like < and > into their respective HTML entities, thereby rendering them harmless. This function improves data sanitization by ensuring that user input is displayed as text rather than being interpreted as code.

// Using htmlspecialchars() to prevent XSS attacks and improve data sanitization
$user_input = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$sanitized_input = htmlspecialchars($user_input);
echo $sanitized_input;