PHP在文本文件中爆炸多行文本

问题描述 投票:1回答:3

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

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
)

我还是新手,我希望有人可以帮助我。提前致谢

php laravel api explode
3个回答
2
投票

试试这个

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

1
投票

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

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


1
投票

请尝试以下代码

public function readfile() 
{
    $file = Storage::get('upload/test.txt');   
    $fileData = [];
    while (!$file->eof()) {
        $fileData[] = $file->fgetcsv(",");
    }
    print_r($fileData);
}
© www.soinside.com 2019 - 2024. All rights reserved.