How can the use of htmlspecialchars() function improve the security and output of data in PHP?

The use of the htmlspecialchars() function in PHP helps improve security by converting special characters into their HTML entities, preventing cross-site scripting attacks. This function ensures that user input is displayed as text on the webpage rather than being interpreted as HTML or JavaScript code, reducing the risk of malicious code execution.

$user_input = "<script>alert('XSS attack');</script>";
$clean_input = htmlspecialchars($user_input);
echo $clean_input;