【问题标题】:PHP replace token in html email variable before sendingPHP在发送前替换html电子邮件变量中的令牌
【发布时间】:2012-07-24 22:59:38
【问题描述】:

我有一封电子邮件要发送给我网站的订阅者。我通过从我的数据库中获取订阅者列表并循环遍历数组并一次发送一封电子邮件来做到这一点......我知道有一种方法可以一次发送所有内容,但这就是我这样做的原因我需要帮助...

HTML 电子邮件包含 2 个标记:

{name}{date}

我需要做的是在 HTML 电子邮件中插入日期以替换 {date} 令牌,并为每封电子邮件插入替换 {name} 的名称(因为名称总是不同的)。

这就是我所拥有的:

        $result = $wpdb->get_results( "SELECT * FROM wp_newsletter WHERE `id` IN ( $userIds )");
        for($i = 0, $size = sizeof($result); $i < $size; ++$i){
          add_filter('wp_mail_content_type',create_function('', 'return "text/html";'));
          $to .= $result[$i]->name.'<'.$result[$i]->email.'>';
          $mail = wp_mail( $to, $subject , $message, $headers);
        }

正如你在上面看到的,我有两个来自数据库的变量:

$result[$i]-&gt;name

$result[$i]-&gt;email

$message 是 HTML 电子邮件正文,其中包含需要替换的 2 个标记。

所以....循环和发送的一切都按预期工作我只需要一些帮助来了解如何为{name}{date} 进行令牌替换。

对此的任何帮助将不胜感激。

【问题讨论】:

  • 感谢@zerkms,非常感谢

标签: php token


【解决方案1】:

这很容易通过 PHP 的 str_replace 函数 docs here 完成。

...
$message = str_replace('{name}', $result[$i]->name, $message);
$message = str_replace('{date}', date('Y/m/d H:i:s'), $message);  // Or your preferred date format

$mail = wp_mail( $to, $subject , $message, $headers);

请注意,如果您知道只有一个 {name} 和/或 {date} 实例,您可以将第四个参数 $count 传递给 str_replace,它会在替换第一个匹配项后退出。

干杯

【讨论】:

  • ok.. @Madbreaks .. 我有一个问题,它发送的所有电子邮件都只包含循环中的名字。有什么想法吗?我猜想当它再次循环时它具有名字实例并且没有记录令牌。
  • 没关系.. 我这样做了:for($i = 0, $size = sizeof($result); $i &lt; $size; ++$i){ $newMessage = $message; $newMessage = str_replace('{name}', $result[$i]-&gt;name, $newMessage); $newMessage = str_replace('{date}', date('F j, Y'), $newMessage); add_filter('wp_mail_content_type',create_function('', 'return "text/html";')); $to .= $result[$i]-&gt;name.'&lt;'.$result[$i]-&gt;email.'&gt;'; $mail = wp_mail( $to, $subject , $newMessage, $headers);
【解决方案2】:
$message = str_replace('{name}',$result[$i]->name,$message);
$message = str_replace('{date}',date('Y/m/d H:i:s'),$message);

str_replace('{name}',$result[$i]->name);
str_replace('{date}',date('Y/m/d H:i:s'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多