0

I'm using matlab excel plugin for convert excel to array. My code is:-

public static function ImportExcel($table="", $path=""){
    $data = array();
    Excel::load($path, function ($reader) use($data) {
        $data = $reader->toArray();
        //here data has all excel data in array.
    });
    return $data; //but here it shows empty array.
}

Check my comments in code. Inside the Excel::load data has array of all data. But its scope is only inside the Excel::load. I need it outside.

Sahil Gupta
  • 578
  • 5
  • 16

3 Answers3

2

The load has an internal function, thus the variables are enclosed inside that function and it also cannot access variables from outside this function, unless they are passed to the function with the use statement. In other words, $data inside the function does not reference to the $data outside it. In order to fix this you will have to add $data to the use statement like this:

public static function ImportExcel($table="", $path=""){
    $data = array();
    Excel::load($path, function ($reader) use($table, $data) {
        $data = $reader->toArray();
        //here data has all excel data in array.
    });
    return $data; //but here it shows empty array.
}
Sven Hakvoort
  • 3,543
  • 2
  • 17
  • 34
2

try this way

$data = Excel::load($path, function ($reader) use($table) {
        $data = $reader->toArray();
        //here data has all excel data in array.
});

otherwise create array before and after clousers

$array = [];
Excel::load($path, function ($reader) use($table, $array) {
    $array = $reader->toArray();
    //here data has all excel data in array.
});

third way doing like that

$results = Excel::load($path);
$data = $results->toArray();
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
2

I write an answer with more detail for another persons who wants to use Maatwebsite\Excel :

if ($request->hasFile('imported_file')){
    $updateFile = $request->file('imported_file');
    
    $path = $updateFile->getRealPath();
    $fileExtension = $updateFile->getClientOriginalExtension();
    
    $formats = ['xls', 'xlsx', 'ods', 'csv'];
    if (! in_array($fileExtension, $formats)) {
        return back()->with("status", 'The uploaded file format is not allowed.');
    }
    
    $data = Excel::load($path, function ($reader) {}, 'UTF-8')->get();
    
    if (! empty($data) && $data->count()) {
        $data = $data->toArray();
        foreach ($data as $perData) {
            // Do whatever you like on per data in your imported data
        }
    }
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Hamid Naghipour
  • 3,465
  • 2
  • 26
  • 55