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.

3 Answers 3

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.
}
Sign up to request clarification or add additional context in comments.

1 Comment

No, Still it returns empty array.
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();

2 Comments

@SahilGupta try third way
Version 3 doesn't have the load method stackoverflow.com/a/49473174/2543240
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
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.