Reputation: 3
I am trying to pass arrays coming from a database and loop them in the email template using phpMailer.
Using following script I can pass single variables and print them in the template:
$message = file_get_contents('template.php');
$message = str_replace('%lname%', $lname, $message);
// Setup PHPMailer
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SetFrom('[email protected]','mywebsite.com');
$mail->AddAddress('[email protected]');
$mail->Subject = 'New message';
$mail->MsgHTML($message);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
Now I would like to pass arrays coming from a database to the related template.
How can I pass them?
Upvotes: 0
Views: 798
Reputation: 111
You can use simple render function
function render($template, $data )
{
extract($data);
ob_start();
include( $template );
$content = ob_get_contents();
ob_end_clean();
return $content;
}
$body = render(__DIR__.'/template.php' , ['first' => 'This is first line' , 'second' => 'this is second line']);
template.php
<table>
<tr>
<td><?=$first ?></td>
</tr>
<tr>
<td><?=$second ?></td>
</tr>
Then send message
$mail = new PHPMailer;
$mail->CharSet = "UTF-8";
$mail->setFrom( $from, 'Mailer');
$mail->addAddress($to);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->send();
Upvotes: 1
Reputation: 37750
You can just repeat that process for as many tags as you want, but note that there are several search & replace functions in PHP like str_replace that accept arrays so you can do many at once.
If you want to get more sophisticated, you can use a template engine like Smarty or Twig.
Overall this has nothing to do with PHPMailer - it will just send whatever you generate, it's an entirely separate thing.
Upvotes: 0