How can PHP be used to format and structure data from a database into a table for email transmission, considering compatibility with email clients like Outlook?
To format and structure data from a database into a table for email transmission, especially for compatibility with email clients like Outlook, you can use PHP to generate HTML code for the table. This HTML code can then be included in the email body to ensure proper formatting and display in various email clients. It is important to use inline styles for the table elements to ensure consistent rendering across different email clients.
// Retrieve data from database
$data = fetchDataFromDatabase();
// Start building the HTML table
$html = '<table style="border-collapse: collapse; width: 100%;">';
$html .= '<tr><th>Name</th><th>Email</th></tr>';
foreach ($data as $row) {
$html .= '<tr>';
$html .= '<td style="border: 1px solid #000; padding: 5px;">' . $row['name'] . '</td>';
$html .= '<td style="border: 1px solid #000; padding: 5px;">' . $row['email'] . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
// Include the HTML table in the email body
$emailBody = '<html><body>';
$emailBody .= '<p>Here is the data from the database:</p>';
$emailBody .= $html;
$emailBody .= '</body></html>';
// Send the email using PHP's mail function
$to = 'recipient@example.com';
$subject = 'Data from Database';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: sender@example.com' . "\r\n";
mail($to, $subject, $emailBody, $headers);