What are the best practices for handling output context in PHP to prevent security vulnerabilities?

Output context in PHP refers to the environment in which output is displayed, such as HTML, JSON, or plain text. To prevent security vulnerabilities, it is essential to properly escape output data based on the context in which it will be displayed. This helps to prevent cross-site scripting (XSS) attacks by ensuring that any user input is properly sanitized before being output to the user.

// Example of escaping output based on context to prevent XSS attacks
$user_input = "<script>alert('XSS attack!')</script>";

// Escaping output for HTML context
$html_output = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo "HTML output: $html_output";

// Escaping output for JSON context
$json_output = json_encode($user_input);
echo "JSON output: $json_output";

// Escaping output for plain text context
$text_output = htmlentities($user_input, ENT_QUOTES, 'UTF-8');
echo "Text output: $text_output";