PHP使用循环数据发送电子邮件

时间:2012-09-08 08:29:30

标签: php

您好我想发送带有php邮件功能的循环数据,这是我的代码:

foreach ($data['query'] as $row){
    echo $row->name;
    echo "<br>";
    echo $row->time;
    echo "<br>";
    echo $row->dosage;
    echo "<br>";
    echo $row->frequency;
    echo "<br>";
    echo $row->quantity;
    echo "<br>";
}

$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com";
mail($to,$subject,$txt,$headers);

任何人都可以告诉我如何将foreach循环数据附加到电子邮件正文中,我的意思是代替发送此文本(Hello World!)而不是发送循环数据。

4 个答案:

答案 0 :(得分:1)

连接$txt

$txt = "";
foreach ($data['query'] as $row){
    $txt .= $row->name;
    $txt .= "<br>";
    $txt .= $row->time;
    $txt .= "<br>";
    $txt .= $row->dosage;
    $txt .= "<br>";
    $txt .= $row->frequency;
    $txt .= "<br>";
    $txt .= $row->quantity;
    $txt .= "<br>";
}

$to = "somebody@example.com";
$subject = "My subject";
$headers = "From: webmaster@example.com";
mail($to,$subject,$txt,$headers);

答案 1 :(得分:1)

纯粹的字符串连接如下:

   $str = ''; 
   foreach ($data['query'] as $row){
      $str .= $row->name;
      $str .= "<br>";
      $str .= $row->time;
      $str .= "<br>";
      $str .= $row->dosage;
      $str .= "<br>";
      $str .= $row->frequency;
      $str .= "<br>";
      $str .= $row->quantity;
      $str .= "<br>";
    }

    $to = "somebody@example.com";
    $subject = "My subject";
    $headers = "From: webmaster@example.com";
    mail($to,$subject,$str,$headers);

    $str = ''; // empty the $str again

答案 2 :(得分:0)

我认为这就是你所追求的目标:

    $to = "somebody@example.com";
    $subject = "My subject";
    $txt = "Hello world!";
    $headers = "From: webmaster@example.com";

    foreach ( $data['query'] as $row ) {
      $txt = $row->name;
      $txt .= "<br>";
      $txt .= $row->time;
      $txt .= "<br>";
      $txt .= $row->dosage;
      $txt .= "<br>";
      $txt .= $row->frequency;
      $txt .= "<br>";
      $txt .= $row->quantity;
      $txt .= "<br>";

      mail( $to, $subject, $txt, $headers );
    }

这会为每个循环发送一封邮件。你的问题不清楚你是否想要那个。您也可以收集所有数据,并将其作为1封电子邮件发送:

$to = "somebody@example.com";
$subject = "My subject";
$txt = "";
$headers = "From: webmaster@example.com";

foreach ( $data['query'] as $row ) {
  $txt .= $row->name;
  $txt .= "<br>";
  $txt .= $row->time;
  $txt .= "<br>";
  $txt .= $row->dosage;
  $txt .= "<br>";
  $txt .= $row->frequency;
  $txt .= "<br>";
  $txt .= $row->quantity;
  $txt .= "-- end of row<br>";

}

mail( $to, $subject, $txt, $headers );

答案 3 :(得分:0)

<?php
$dataArray  =   array('name','time','dosage','frequency','quantity');
$txt        =   '';
foreach ($data['query'] as $row)
{
    foreach($dataArray as $key=>$data)
    {
       $txt .= ($row->$data.'</br>');
    }
}

$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com";
mail($to,$subject,$txt,$headers);

?>