What is the significance of using htmlspecialchars() for context switching in PHP?
When switching contexts in PHP, such as when outputting user input to HTML, it is important to use htmlspecialchars() to prevent cross-site scripting (XSS) attacks. This function converts special characters like < and > into their HTML entity equivalents, ensuring that any user input is displayed as plain text rather than interpreted as HTML code.
$user_input = "<script>alert('XSS attack!');</script>";
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');