How can PHP developers prevent potential XSS attacks when outputting data from a text file into an HTML context?

To prevent potential XSS attacks when outputting data from a text file into an HTML context, PHP developers can use the htmlspecialchars function to encode the data before displaying it on the webpage. This function will convert special characters like < and > into their HTML entity equivalents, rendering them harmless to the browser.

&lt;?php
// Read data from a text file
$data = file_get_contents(&#039;data.txt&#039;);

// Output the data on the webpage after encoding it
echo htmlspecialchars($data, ENT_QUOTES);
?&gt;