Vladimir Jovanović Vladimir Jovanović - 15 days ago 10
PHP Question

Slim framework and email template rendering issue with PHPmailer

I am using Slim v3 php framework and have integrated PHPMailer to send mails. I don't use any template engine like Twig, but I rather use plain PHP.

My idea is to make a HTML5 template for emails in a separate file, similar to regular page templates and then pass some variables into it, render it and send it. It all works well except for one part - rendered output also has rendered header info.

This is how my code looks like, simplified of course

// Store variables in an array
$email_content = array(
'email__name' => $_POST['name'],
'email__from' => $_POST['from'],
'email__message' => $_POST['message']
);

// Render email template
$template = $this->view->render($response, "email/simple_email.phtml", $email_content);


And then I send this with PHPMailer

$mail->msgHTML($template);


Problem is that on top of HTML content I get this header data, which is visible in sent email:

HTTP/1.1 200 OK Content-Type: text/html; charset=UTF-8


Is there a way to render output without this? At the moment I am using str_replace() to remove this, but I guess that there is an elegant, built in, solution to deal with this?

Answer

The #render() method returns a Psr\Http\Message\ResponseInterface which contains all information about the response so also the header informations.

You only want the html so use the #fetch() method on the view which returns only the html.

$template = $this->view->fetch("email/simple_email.phtml", $email_content);
Comments