Search code examples
phpmodel-view-controllerphpmailer

Capturing MVC PHP view into a variable to pass as body mail in PHPMailer


I'm using a MVC framework and i want to pass a view into PHPMailer body but I can't capture the view into a variable.

Controller handling view looks like this:

// Load View
public function view($view, $data = []){
    // Check for view file
    if(file_exists('../app/views/'.$view.'.php')){
        require_once '../app/views/'.$view.'.php';
    }else{
        // View does not exist
        die('View does not exist');
    }
}

In controller i pass the view into the function sendMail but it first loads it than i get an error file_get_contents(): Filename cannot be empty:

$bodyMail = file_get_contents($this->view('booking/mailbody'));

sendEmail($bookingNumber, $id, $mailAddress, $bodyMail);

The helper function to handle PHPMailer function:

function sendEmail($bookingNumber, $id, $mailAddress, $bodyMail){

$mail = new PHPMailer(true);

//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "*********";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "**********";
$mail->Password = "********";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;

$mail->From = "********";
$mail->FromName = "*******";

$mail->addAddress($mailAddress);
$mail->addAddress('*********');

$mail->isHTML(true);

$mail->Subject = "Reservation confirmed: ".$bookingNumber.$id."";
$mail->Body = $bodyMail;
$mail->AltBody = "This is plain text of mail";

try {
    $mail->send();
    echo "Message has been sent successfully";
} catch (Exception $e) {
    echo "Mailer Error: " . $mail->ErrorInfo;
}

My question is there's a way to capture the view into a variable? Would you approach this in a different way? If so, can you guys give me the right direction to take?


Solution

  • As per my comment, I suggest using output buffering to capture the output of your view

    https://www.php.net/manual/en/function.ob-get-clean.php

    And as @synchro suggest, review your usage of require_once()

    // Load View, but capture it with output buffering
    public function viewBuffered($view, $data = []){
        // Check for view file
        if(file_exists('../app/views/'.$view.'.php')){
            ob_start();
            require_once '../app/views/'.$view.'.php';
            return ob_get_clean();
        }else{
            // View does not exist
            die('View does not exist');
        }
    }
    

    -or-

    // Load View, but capture it with output buffering
    public function viewBuffered($view, $data = []){
        ob_start();
        $this->view($view,$data);
        return ob_get_clean();
    }