What are the best practices for escaping characters in PHP to prevent them from being interpreted incorrectly by the browser?

To prevent characters from being interpreted incorrectly by the browser in PHP, it is important to escape special characters that have special meanings in HTML, such as <, >, ", ', and &. This can be done using the htmlspecialchars() function in PHP, which converts these characters into their corresponding HTML entities.

$unsafe_string = &quot;&lt;script&gt;alert(&#039;Hello, world!&#039;);&lt;/script&gt;&quot;;
$safe_string = htmlspecialchars($unsafe_string, ENT_QUOTES, &#039;UTF-8&#039;);
echo $safe_string;