What are the best practices for protecting against XSS (Cross Site Scripting) attacks in PHP applications?

XSS (Cross Site Scripting) attacks occur when a malicious user injects scripts into a website, which are then executed by unsuspecting users. To protect against XSS attacks in PHP applications, it is important to properly sanitize user input and encode output to prevent the execution of malicious scripts.

// Sanitize user input
$userInput = htmlspecialchars($_POST['user_input'], ENT_QUOTES);

// Output encoded data to prevent XSS attacks
echo $userInput;