What are the best practices for outputting variables in PHP?

When outputting variables in PHP, it is important to ensure that the output is secure and properly formatted to prevent any potential security vulnerabilities such as Cross-Site Scripting (XSS) attacks. To achieve this, it is recommended to use htmlspecialchars() function to escape special characters and prevent script injection.

<?php
// Example variable
$variable = "<script>alert('XSS attack')</script>";

// Output the variable using htmlspecialchars() function
echo htmlspecialchars($variable);
?>