2016-12-02 131 views
1

我正在使用以下代碼通過(PHPMailer)發送電子郵件。將變量傳遞給PHPMailer get_file_contents

該腳本從welcome.php(電子郵件模板)獲取文件內容,如何將變量傳遞給模板?所以我可以自定義電子郵件模板。你可以做

// SEND EMAIL NOTIFICATION TO USER 
$mail = new PHPMailer(); 

$body = file_get_contents('emails/templates/carer/welcome.php'); 
$body = eregi_replace("[\]",'',$body); 

$mail->AddReplyTo("[email protected]","CareMatch"); 

$mail->SetFrom('[email protected]', 'Carematch'); 

$address = $_POST['email']; 
$name  = $_POST['firstname'] . $_POST['lastname']; 

$mail->AddAddress($address, $name); 

$mail->Subject = "Welcome to CareMatch"; 

$mail->AltBody = "We have assigned you a unique ID and generated you a password."; // optional, comment out and test 

$mail->MsgHTML($body); 

if(!$mail->Send()) { 
    echo "Mailer Error: " . $mail->ErrorInfo; 
} else { 
    echo "Message sent!"; 
} 
+0

取代'的file_get_contents()',而調用解析爲標籤的模板,並與所要求的內容替換標籤的功能。 – Dragos

回答

1

一種方法是,你可以在你的添加佔位符的welcome.php並取代那些佔位符與實際值,一旦你的內容,使用str_replace()功能,如:

... 
$searchArr = ["YOUR-PLACEHOLDER-FIRST", "YOUR-PLACEHOLDER-SECOND"]; 
$replaceArr = [$yourFirstVariable, $yourSecondVariable] 

$body = file_get_contents('emails/templates/carer/welcome.php'); 
$body = str_replace($searchArr, $replaceArr, $body); 
... 

的palceholders YOUR-PLACEHOLDER-FIRSTYOUR-PLACEHOLDER-SECOND將被添加到的welcome.php文件

+0

humm,它基於模板框架結構? –

1

下面是我使用的功能經常給我PHP模板,使用PHP輸出緩衝區來捕獲渲染模板。

與使用任何種類的查找和替換方法的靜態佔位符數組相比,它提供了更多的靈活性。

function loadTemplate($template, array $properties = array()){ 
    $output = ""; 

    if (file_exists($template)) { 
     extract($properties); 

     ob_start(); 

     require($template); 

     $output = ob_get_contents(); 

     ob_end_clean(); 
    } 

    return $output; 
} 

$data = [ 
    "foo" => "bar" 
]; 

$message = loadTemplate("/path/to/email.phtml", $data); // <p>bar</p> 

email.phtml

<p><?php echo $foo; ?></p>