Read each line of txt file to new array element

PhpArraysText FilesFgets

Php Problem Overview


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);

?>

Php Solutions


Solution 1 - Php

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

$lines = file($filename, FILE_IGNORE_NEW_LINES);

Solution 2 - Php

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.

Solution 3 - Php

Just use this:

$array = explode("\n", file_get_contents('file.txt'));

Solution 4 - Php

$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

Solution 5 - Php

<?php
$file = fopen("members.txt", "r");
$members = array();

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

fclose($file);

var_dump($members);
?>

Solution 6 - Php

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"

Solution 7 - Php

$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.

Solution 8 - Php

$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);

Solution 9 - Php

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);
    ?>

Solution 10 - Php

	$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

Solution 11 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanView Question on Stackoverflow
Solution 1 - PhpYanick RochonView Answer on Stackoverflow
Solution 2 - PhpDrew Dello StrittoView Answer on Stackoverflow
Solution 3 - PhpRoLifeView Answer on Stackoverflow
Solution 4 - PhpiianfumenchuView Answer on Stackoverflow
Solution 5 - PhpGauravView Answer on Stackoverflow
Solution 6 - PhpCodeBrauerView Answer on Stackoverflow
Solution 7 - PhpRafe KettlerView Answer on Stackoverflow
Solution 8 - PhpAttila NagyView Answer on Stackoverflow
Solution 9 - PhpNick AndrenView Answer on Stackoverflow
Solution 10 - PhpaltayevrimView Answer on Stackoverflow
Solution 11 - PhpBrian LeishmanView Answer on Stackoverflow