13

I have txt file with email addresses under under the other like :

test@test.com
test2@test.com

So far I managed to open it with

 $result = file_get_contents("tmp/emails.txt");
but I don't know to to get the email addresses in an array. Basically I could use explode but how do I delimit the new line ? thanks in advance for any answer !
Michael
  • 6,377
  • 14
  • 59
  • 91
  • 1
    The answers below are ideal; but for reference, you could use explode with the newline character, represented as \n. (This may also be \r\n depending on whether you're using Windows or Linux). – user11977 Jul 18 '10 at 09:14

3 Answers3

34

Just read the file using file() and you'll get an array containing each line of the file.

$emails = file('tmp/emails.txt');

To not append newlines to each email address, use the FILE_IGNORE_NEW_LINES flag, and to skip empty lines, use the FILE_SKIP_EMPTY_LINES flag:

$emails = file('tmp/emails.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Doing a var_dump($emails) of the second example gives this:

array(2) {
  [0]=>
  string(13) "test@test.com"
  [1]=>
  string(14) "test2@test.com"
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 2
    THough this works, it doesn't take into account windows based new lines. using preg_split works more reliably. – Zia May 30 '13 at 14:54
11
$lines = preg_split('/\r\n|\n|\r/', trim(file_get_contents('file.txt')));
David
  • 1,155
  • 9
  • 3
2

As crazy as this seems, doing a return or enter inside a double-quote ("") delimits a newline. To make it clear, type in:

explode("", "Stuff to delimit");

and simply hit return at the middle of "", so you get:

explode("

", "stuff to delimit");

and it works. Probably unconventional, and might only work on Linux. But it works.