PHP 分解文本文件中的多行文本

PHP explode multi line text in text file

我有一个文本文件,里面的数据是:

john,male,20,200,174
joe,male,24,157,166
bea,female,18,153,160
edd,male,30,180,180

我正在使用 Laravel,所以我在 storage/app/upload 中有包含此文本文件的文件夹。 在我的控制器中,这是我的代码:

public function readfile() 
    {
        $file = Storage::get('upload/test.txt');        
        $array = explode(',', $file);
        print_r($array);
    }

输出是:

Array
(
    [0] => john
    [1] => male
    [2] => 20
    [3] => 200
    [4] => 174
joe
    [5] => male
    [6] => 24
    [7] => 157
    [8] => 166
bea
    [9] => female
    [10] => 18
    [11] => 153
    [12] => 160
edd
    [13] => male
    [14] => 30
    [15] => 180
    [16] => 180
)

我需要做的是:

Array
(
     [0] => john,male,20,200,174
     [1] => joe,male,24,157,166
     [2] => bea,female,18,153,160
     [3] => edd,male,30,180,180
)

我对此还很陌生,希望有人能帮助我。提前致谢

试试这个

public function readfile() 
    {
        $file = Storage::get('upload/test.txt');        
        $array = explode(PHP_EOL, $file);
        print_r($array);
    }

要获取数组的数组(行-逗号分隔)尝试

public function readfile() 
    $file = Storage::get('upload/test.txt');
    $lines = explode("\n", $file);
    $array = array_map(function($line) {
        return explode(',', $line);
    }, $lines);
    print_r($array);
}

如果您只想获取行数组,那么它在 $lines 中。工作示例 here

试试下面的代码

public function readfile() 
{
    $file = Storage::get('upload/test.txt');   
    $fileData = [];
    while (!$file->eof()) {
        $fileData[] = $file->fgetcsv(",");
    }
    print_r($fileData);
}