使用explode和foreach逐个显示电子邮件

时间:2013-07-14 07:57:14

标签: php foreach explode

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

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”

但是,我正在

“firstemail”, “secondemail”, “thirdemail”, “fourthemail”, “fifthemail”

3 个答案:

答案 0 :(得分:3)

这基本上是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
}

答案 1 :(得分:1)

您的代码应如下所示:

<?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电子邮件:“secondemail” 3电子邮件:“thirdemail” 4电子邮件:“fourthemail” 5电子邮件:“fifthemail”

答案 2 :(得分:0)

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

此代码段假设您不需要编号,而只需要每行中的电子邮件地址。 但正确的代码片段应该是:

<?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!';
}
?>