What are the benefits of using htmlspecialchars function when outputting data in PHP, and how does it prevent potential vulnerabilities?

When outputting data in PHP, it is important to use the htmlspecialchars function to prevent potential cross-site scripting (XSS) attacks. This function converts special characters like < and > into their HTML entities, making it safe to display user input on a webpage without executing any malicious scripts.

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