recovery men recovery men - 10 days ago 6
PHP Question

how to get whole csv file and print (laravel 5.3)

This time i am to get header don't know how can i get whole csv file data and print it
here is my function please help to go forward

public function import(Request $request){
$upload =$request->file('upload-file');
$filepath= $upload->getRealPath();

$file=fopen($filepath, 'r');

$header=fgetcsv($file);
dd($header);
die;
}


I want that header should not come here other than header whole data should be print
its foreach loop

foreach($users as $user) {
}


Here is header which i am getting

array:13 [▼
0 => "Account Name"
1 => "Group"
2 => "Host"
3 => "Username"
4 => "Password"
5 => "Port"
]

Answer

fgetcsv returns the line it's looking at and moves the "pointer" to the next line. If you want to load the entire CSV file into an array you need to loop through the file:

<?php
$data = [];
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    $i = 0; // Define a counter that tells us which row we're looking at
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
        // Only capture rows that are greater than 0, i.e. we skip the first row (Headers)
        if ($i > 0) {
            $data[] = $row;
        }

        $i++;
    }
    fclose($handle);
}

var_dump($data);

Creating a user for each of the rows of data should be easy:

foreach ($data as $item) {
    User::create($item);
}

Regarding validating that the uploaded file is a CSV file you can use Laravel's validation rules, specifically those regarding mimes. For example:

'file' => 'file|mimes:csv'

If you want to do some validation in your function you can use some of the methods on the UploadedFile instance that you get from $request->file('...');, specifically you could use $upload->getClientOriginalExtension() to get the file extension of the file that was uploaded, or you could use $upload->getClientMimeType() to get the mime type of the file, which in the case of a CSV should be text/csv:

if ($upload->getClientOriginalExtension() != 'csv') {
    // Handle your validation error, probably throw an exception
}

if ($upload->getClientMimeType() != 'text/csv') {
    // Handle error
}
Comments