What best practices should be followed when assigning a string for output in a template object in PHP?

When assigning a string for output in a template object in PHP, it is important to properly escape the string to prevent any potential security vulnerabilities such as cross-site scripting (XSS) attacks. One common method to achieve this is by using the htmlentities() function to convert special characters to their HTML entities. This ensures that the string is safely outputted in the template without causing any harm.

// Assigning a string for output in a template object
$string = "<script>alert('XSS attack!');</script>";

// Escaping the string using htmlentities() function
$escapedString = htmlentities($string);

// Output the escaped string in the template
echo $escapedString;