How can you prevent XSS attacks when outputting user input in PHP?

To prevent XSS attacks when outputting user input in PHP, you should always sanitize and validate user input before displaying it on a webpage. One common method is to use the htmlspecialchars() function to escape special characters that could be interpreted as HTML or JavaScript code. This helps to prevent malicious scripts from being executed in the browser.

$userInput = $_POST['user_input']; // Assuming user input is received via POST method
$cleanInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
echo $cleanInput;