How should context switches be handled when applying htmlspecialchars in PHP?

When applying htmlspecialchars in PHP, it is important to handle context switches properly to ensure that the data is being encoded correctly based on where it will be displayed. For example, if the data will be displayed in an HTML attribute, the encoding requirements are different compared to displaying it within the body of an HTML document. To handle context switches, you can use different encoding options provided by the htmlspecialchars function, such as ENT_QUOTES for encoding double quotes within HTML attributes.

// Example of handling context switches when applying htmlspecialchars in PHP
$data = '<script>alert("Hello World")</script>';
// Encoding for displaying within HTML body
echo htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
// Encoding for displaying within HTML attribute
echo htmlspecialchars($data, ENT_QUOTES | ENT_HTML5, 'UTF-8');