【问题标题】:display email one by one using explode and foreach使用explode和foreach一一显示电子邮件
【发布时间】:2013-07-14 07:57:13
【问题描述】:

我正在尝试一个一个地循环显示电子邮件地址。但是,它只是在一行中打印所有电子邮件地址。

email.txt

"firstemail","secondemail","thirdemail","fourthemail","fifthemail"

email.php

<?php 
$count=1;
$emails=readfile("../email.txt");
$email=explode(",",$emails);
foreach($email as $e){
    echo "$count Email : $e<br />\n";
$count=$count+1;
}
?>

预期输出

“第一封邮件”

“第二封邮件”

“第三封电子邮件”

“四信”

“第五封邮件”

但是,我得到了

"firstemail","secondemail","thirdemail","fourthemail","fifthemail"

【问题讨论】:

  • 顺便说一句:第 4 行中缺少 $explode (",", $emails);
  • 这是唯一的代码,我现在有。
  • @Casper 已更改,但问题仍然相同。
  • 您是在创建网页还是文本文件?
  • 网页?为什么 ?不..我只是想从email.txt文件中逐行打印电子邮件地址。

标签: php foreach explode


【解决方案1】:

这基本上就是readfile() 所做的;它读取文件并输出它。返回值是读取了多少字节(我在您的输出中没有看到)。

我承认对于这样一个函数来说这是一个非常糟糕的名字,但这是你在 PHP 中开发时会看到的有趣的东西 :-)

无论如何,你要找的函数是file_get_contents()

$emails = file_get_contents("../email.txt");

更新

在我看来,您实际上是在寻找fgetcsv()

$f = fopen('../email.txt', 'rt');
while (!feof($f)) {
    $row = fgetcsv($f);
    if ($row == false || $row[0] === null) {
        continue;
    }
    // $row is an array comprising the email addresses on one line
}

【讨论】:

    【解决方案2】:

    您的代码应如下所示:

    <?php 
    $count=1;
    $emails= file_get_contents("../email.txt");
    $email=explode(",",$emails);
    foreach($email as $e){
        echo "$count Email : $e<br />\n";
    $count=$count+1;
    }
    ?>
    

    输出: 1 封电子邮件:“firstemail” 2 电子邮件:“第二个电子邮件” 3 电子邮件:“第三个电子邮件” 4 电子邮件:“fourthemail” 5 电子邮件:“fifthemail”

    【讨论】:

      【解决方案3】:

      显示的代码与您提到的输出不对应...

      此代码 sn-p 假定您不需要编号,而只需要每行中的电子邮件地址。 但是正确的代码 sn-p 应该是这样的:

      <?php
      if (file_exists('../email.txt'))
      {
         $file_contents = file_get_contents('../email.txt');
         $emails = explode(',', $file_contents);
         foreach ($emails as $e)
         {
            echo $e."<br>\n";
         }
      }
      else
      { 
         echo 'file does not exist!';
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 2012-08-31
        • 1970-01-01
        • 1970-01-01
        • 2012-12-29
        • 2013-07-11
        • 2012-11-25
        • 1970-01-01
        • 2015-04-24
        • 1970-01-01
        相关资源
        最近更新 更多