How can output context be secured in PHP to prevent vulnerabilities like XSS attacks when displaying data in HTML?

To secure output context in PHP and prevent vulnerabilities like XSS attacks when displaying data in HTML, you can use the htmlspecialchars function to encode special characters in the output. This function converts characters like <, >, ", ', and & into their HTML entity equivalents, ensuring that they are displayed as plain text and not interpreted as HTML tags.

&lt;?php
// Data to be displayed
$data = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;)&lt;/script&gt;&quot;;

// Securely output the data in HTML
echo htmlspecialchars($data, ENT_QUOTES, &#039;UTF-8&#039;);
?&gt;