How can PHP developers securely output a string containing PHP code and HTML content?

PHP developers can securely output a string containing PHP code and HTML content by using the htmlspecialchars() function to escape special characters in the string. This prevents any potential XSS attacks by converting characters like < and > into their HTML entity equivalents. By using htmlspecialchars(), developers can ensure that the output is safe to be displayed in the browser.

&lt;?php
$string = &#039;&lt;script&gt;alert(&quot;XSS attack&quot;)&lt;/script&gt;&#039;;
echo htmlspecialchars($string);
?&gt;