139

I am trying to read every line of a text file into an array and have each line in a new element.
My code so far.

<?php
$file = fopen("members.txt", "r");
while (!feof($file)) {

$line_of_text = fgets($file);
$members = explode('\n', $line_of_text);
fclose($file);

?>
Vaggelis Manousakis
  • 292
  • 1
  • 5
  • 15
Dan
  • 1,407
  • 3
  • 11
  • 4

11 Answers11

425

If you don't need any special processing, this should do what you're looking for

$lines = file($filename, FILE_IGNORE_NEW_LINES);
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
  • 2
    `file()` seems to be considerably slower than `file_get_contents` + `explode` to array – Ron Jul 09 '20 at 13:38
  • 3
    @Ron I agree. Then again, you shouldn't read a file this way at every request. That's just silly, even if the solution is optimal. The content of the file should either be stored on memory cache, or even in a database. Even PHP stores the content of parsed files. I mean, we're far from PHP 4.3 – Yanick Rochon Jul 16 '20 at 02:32
46

The fastest way that I've found is:

// Open the file
$fp = @fopen($filename, 'r'); 

// Add each line to an array
if ($fp) {
   $array = explode("\n", fread($fp, filesize($filename)));
}

where $filename is going to be the path & name of your file, eg. ../filename.txt.

Depending how you've set up your text file, you'll have might have to play around with the \n bit.

Peter Stuart
  • 2,362
  • 7
  • 42
  • 73
  • 6
    I would use "PHP_EOL" instead of "\n", this looks so, $array = explode(PHP_EOL, fread($fp, filesize($filename))); – LFS96 Feb 27 '16 at 11:43
  • Thanks Drew, after trying many functions, yours is the only one that worked. My search term being
    instead of your \n. My file was being read as only a single big value array, whole text was just one array item $myarr[0], so shuffling did not work on a single item. Hope it helps someone. Thanks again.
    – washere Apr 21 '17 at 21:54
37

Just use this:

$array = explode("\n", file_get_contents('file.txt'));
RoLife
  • 489
  • 4
  • 5
30
$yourArray = file("pathToFile.txt", FILE_IGNORE_NEW_LINES);

FILE_IGNORE_NEW_LINES avoid to add newline at the end of each array element
You can also use FILE_SKIP_EMPTY_LINES to Skip empty lines

reference here

iianfumenchu
  • 898
  • 9
  • 14
23
<?php
$file = fopen("members.txt", "r");
$members = array();

while (!feof($file)) {
   $members[] = fgets($file);
}

fclose($file);

var_dump($members);
?>
Gaurav
  • 28,447
  • 8
  • 50
  • 80
  • 1
    Okay I have it working perfectly thanks. However I need to set a vaiable = to an array element. $var = $ary[1]; does not work. ary[1]= "test". If that helps. – Dan May 28 '11 at 05:22
  • 1
    Run a counter yourself and set the index in the array – Prasad Sep 23 '12 at 06:45
  • [why `while(!feof($file))` is wrong](https://stackoverflow.com/questions/34425804/php-while-loop-feof-isnt-outputting-showing-everything) – Barmar Jun 02 '21 at 18:37
13

It's just easy as that:

$lines = explode("\n", file_get_contents('foo.txt'));

file_get_contents() - gets the whole file as string.

explode("\n") - will split the string with the delimiter "\n" - what is ASCII-LF escape for a newline.

But pay attention - check that the file has UNIX-Line endings.

If "\n" will not work properly you have another coding of newline and you can try "\r\n", "\r" or "\025"

CodeBrauer
  • 2,690
  • 1
  • 26
  • 51
7
$lines = array();
while (($line = fgets($file)) !== false)
    array_push($lines, $line);

Obviously, you'll need to create a file handle first and store it in $file.

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
3
$file = __DIR__."/file1.txt";
$f = fopen($file, "r");
$array1 = array();

while ( $line = fgets($f, 1000) )
{
    $nl = mb_strtolower($line,'UTF-8');
    $array1[] = $nl;
}

print_r($array);
Attila Nagy
  • 91
  • 1
  • 1
1
    $file = file("links.txt");
print_r($file);

This will be accept the txt file as array. So write anything to the links.txt file (use one line for one element) after, run this page :) your array will be $file

altayevrim
  • 29
  • 3
1

You were on the right track, but there were some problems with the code you posted. First of all, there was no closing bracket for the while loop. Secondly, $line_of_text would be overwritten with every loop iteration, which is fixed by changing the = to a .= in the loop. Third, you're exploding the literal characters '\n' and not an actual newline; in PHP, single quotes will denote literal characters, but double quotes will actually interpret escaped characters and variables.

    <?php
        $file = fopen("members.txt", "r");
        $i = 0;
        while (!feof($file)) {
            $line_of_text .= fgets($file);
        }
        $members = explode("\n", $line_of_text);
        fclose($file);
        print_r($members);
    ?>
Nick Andren
  • 204
  • 2
  • 4
0

This has been covered here quite well, but if you REALLY need even better performance than anything listed here, you can use this approach that uses strtok.

$Names_Keys = [];
$Name = strtok(file_get_contents($file), "\n");
while ($Name !== false) {
    $Names_Keys[$Name] = 0;
    $Name = strtok("\n");
}

Note, this assumes your file is saved with \n as the newline character (you can update that as need be), and it also stores the words/names/lines as the array keys instead of the values, so that you can use it as a lookup table, allowing the use of isset (much, much faster), instead of in_array.

Brian Leishman
  • 8,155
  • 11
  • 57
  • 93