Read each line of txt file to new array element

2019-01-03 04:38发布

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");
$i = 0;
while (!feof($file)) {

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

?>

11条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-03 04:57
$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.

查看更多
我命由我不由天
3楼-- · 2019-01-03 04:59

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 a other coding of2 newline and you can try "\r\n", "\r" or "\025"

查看更多
Ridiculous、
4楼-- · 2019-01-03 05:02
$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);
查看更多
家丑人穷心不美
5楼-- · 2019-01-03 05:05

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);
    ?>
查看更多
太酷不给撩
6楼-- · 2019-01-03 05:11
    $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

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-03 05:15
$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

查看更多
登录 后发表回答