3

我有一个发送站点电子邮件的功能(使用 phpmailer),我想要做的基本上是让 php 用我提供的内容替换 email.tpl 文件中的所有占位符。对我来说,问题是我不想重复代码,因此我创建了一个函数(如下)。

如果没有 php 函数,我会在脚本中执行以下操作

// email template file
$email_template = "email.tpl";

// Get contact form template from file
$message = file_get_contents($email_template);

// Replace place holders in email template
$message = str_replace("[{USERNAME}]", $username, $message);
$message = str_replace("[{EMAIL}]", $email, $message);

现在我知道如何做剩下的了,但我卡在了str_replace(),如上所示,我有多个str_replace()函数来替换电子邮件模板中的占位符。我想要的是添加str_replace()到我的函数(如下)并让它[\]在我给它的电子邮件模板中找到所有实例并将其替换为我将给它的占位符值,如下所示:str_replace("[\]", 'replace_with', $email_body)

问题是我不知道如何将多个占位符及其替换值传递到我的函数中,并让str_replace("[{\}]", 'replace_with', $email_body)处理我给它的所有占位符并用相应的值替换。

因为我想在多个地方使用该函数并避免重复代码,所以在某些脚本上我可能会传递函数 5 个占位符和值,而另一个脚本可能需要将 10 个占位符和值传递给要在电子邮件模板中使用的函数。

我不确定我是否需要在将使用函数的脚本上使用一个数组,并在函数中使用一个for循环,也许可以让我的 php 函数从脚本中获取 xx 占位符和 xx 值并遍历占位符并用那里的值替换它们。

这是我上面提到的我的功能。我评论了可能更容易解释的脚本。

// WILL NEED TO PASS PERHAPS AN ARRAY OF MY PLACEHOLDERS AND THERE VALUES FROM x SCRIPT
// INTO THE FUNCTION ?
function phpmailer($to_email, $email_subject, $email_body, $email_tpl) {

// include php mailer class
require_once("class.phpmailer.php");

// send to email (receipent)
global $to_email;
// add the body for mail
global $email_subject;
// email message body
global $email_body;
// email template
global $email_tpl;

// get email template
$message = file_get_contents($email_tpl);

// replace email template placeholders with content from x script
// FIND ALL INSTANCES OF [{}] IN EMAIL TEMPLATE THAT I FEED THE FUNCTION 
// WITH AND REPLACE IT WITH THERE CORRESPOING VALUES.
// NOT SURE IF I NEED A FOR LOOP HERE PERHAPS TO LOOP THROUGH ALL 
// PLACEHOLDERS I FEED THE FUNCTION WITH AND REPLACE WITH THERE CORRESPONDING VALUES
$email_body       = str_replace("[{\}]", 'replace', $email_body);

// create object of PHPMailer
$mail = new PHPMailer();

// inform class to use smtp
$mail->IsSMTP();
// enable smtp authentication
$mail->SMTPAuth   = SMTP_AUTH;
// host of the smtp server
$mail->Host       = SMTP_HOST;
// port of the smtp server
$mail->Port       = SMTP_PORT;
// smtp user name
$mail->Username   = SMTP_USER;
// smtp user password
$mail->Password   = SMTP_PASS;
// mail charset
$mail->CharSet    = MAIL_CHARSET;

// set from email address
$mail->SetFrom(FROM_EMAIL);
// to address
$mail->AddAddress($to_email);
// email subject
$mail->Subject = $email_subject;
// html message body
$mail->MsgHTML($email_body);
// plain text message body (no html)
$mail->AltBody(strip_tags($email_body));

// finally send the mail
if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
  } else {
  echo "Message sent Successfully!";
  }
}
4

3 回答 3

16

很简单,请参阅strtr文档

$vars = array(
    "[{USERNAME}]" => $username,
    "[{EMAIL}]" => $email,
);

$message = strtr($message, $vars);

根据需要添加尽可能多(或更少)的替换对。但我建议,你在调用phpmailer函数之前处理模板,所以事情是分开的:模板和邮件发送:

class MessageTemplateFile
{
    /**
     * @var string
     */
    private $file;
    /**
     * @var string[] varname => string value
     */
    private $vars;

    public function __construct($file, array $vars = array())
    {
        $this->file = (string)$file;
        $this->setVars($vars);
    }

    public function setVars(array $vars)
    {
        $this->vars = $vars;
    }

    public function getTemplateText()
    {
        return file_get_contents($this->file);
    }

    public function __toString()
    {
        return strtr($this->getTemplateText(), $this->getReplacementPairs());
    }

    private function getReplacementPairs()
    {
        $pairs = array();
        foreach ($this->vars as $name => $value)
        {
            $key = sprintf('[{%s}]', strtoupper($name));
            $pairs[$key] = (string)$value;
        }
        return $pairs;
    }
}

然后可以大大简化使用,您可以将整个模板传递给任何需要字符串输入的函数。

$vars = compact('username', 'message');
$message = new MessageTemplateFile('email.tpl', $vars);
于 2012-04-11T12:40:43.083 回答
1

PHP 解决方案可以是:

在 Programmers.StackExchange 找到广泛的答案,以了解有关PHP 电子邮件模板的其他方法。

于 2016-05-17T21:26:22.080 回答
0

你为什么不把电子邮件模板也做成一个 php 文件呢?然后您可以执行以下操作:

Hello <?=$name?>, my name is <?=$your_name?>, today is <?=$date?>

在电子邮件中生成 HTML,然后将结果作为电子邮件发送。

在我看来,你的做法很艰难?

于 2012-04-11T12:44:39.537 回答