What are some best practices for converting special characters to HTML entities in PHP?

When dealing with special characters in PHP, it's important to convert them to HTML entities to ensure they display correctly in web browsers. This can help prevent security vulnerabilities like cross-site scripting attacks. One way to do this is by using the htmlspecialchars() function in PHP, which converts special characters to their corresponding HTML entities.

$special_string = "<h1>Hello, world!</h1>";
$encoded_string = htmlspecialchars($special_string, ENT_QUOTES, 'UTF-8');
echo $encoded_string;