Can you provide examples of securely outputting PHP strings within HTML tags?

When outputting PHP strings within HTML tags, it is important to ensure that the output is secure to prevent any potential security vulnerabilities such as cross-site scripting (XSS) attacks. To securely output PHP strings within HTML tags, you can use the htmlspecialchars() function in PHP to encode special characters and prevent them from being interpreted as HTML. Example PHP code snippet:

<?php
// Define a PHP string variable
$string = "<script>alert('XSS attack!');</script>";

// Output the PHP string securely within HTML tags using htmlspecialchars()
echo "<p>" . htmlspecialchars($string) . "</p>";
?>