[php] Read each line of txt file to new array element

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

?>

This question is related to php arrays text-files fgets

The answer is


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

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

fclose($file);

var_dump($members);
?>

$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


    $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


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

$lines = file($filename, FILE_IGNORE_NEW_LINES);

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


Just use this:

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

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

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.


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

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.


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"


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to text-files

How to edit a text file in my terminal Reading specific columns from a text file in python Read a local text file using Javascript Split text file into smaller multiple text file using command line How do I read a text file of about 2 GB? Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList? Copying from one text file to another using Python Getting all file names from a folder using C# Reading From A Text File - Batch How to import data from text file to mysql database

Examples related to fgets

Read each line of txt file to new array element How to read from stdin with fgets()? Removing trailing newline character from fgets() input Why is the gets function so dangerous that it should not be used?