What are some best practices for formatting and structuring HTML content, including variables, to be included in the body of an email using PHP?

When formatting and structuring HTML content to be included in the body of an email using PHP, it is important to properly encode any variables to prevent injection attacks and ensure proper rendering of special characters. One best practice is to use PHP's htmlspecialchars function to encode variables before inserting them into the HTML content. Additionally, using inline CSS styles for formatting can help ensure consistent rendering across different email clients.

// Example of formatting and structuring HTML content for an email using PHP

// Define variables
$name = "John Doe";
$message = "Hello, <b>$name</b>!";

// Encode variables
$name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
$message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');

// Construct HTML content
$html_content = "
<html>
<head>
<style>
body {
  font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<p>$message</p>
</body>
</html>
";

// Send email
$to = "recipient@example.com";
$subject = "Test Email";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: sender@example.com\r\n";

mail($to, $subject, $html_content, $headers);