Search code examples
phplaravelapiexplode

PHP explode multi line text in text file


I have a text file and the data inside is:

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

I am using Laravel and so I have the folder containing this text file in storage/app/upload. In my controller this is my code:

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

the output is:

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
)

what I NEED to happen is this:

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
)

I am still new to this and I hope someone can help me. Thanks in advance


Solution

  • Try this

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