Mr. Sam
Mr. Sam

Reputation: 790

PHP skip undefined offset in foreach loop?

I'm trying to scan hundreds of folders each containing an excel file.

Here's the simplified workflow

Ok so all this is working just fine, except when i run into an excel file which is corrupted.

The problem then is that the PHPEXCEL library cant read it and it throughs back a "Notice: Undefined offset:" and this breaks my foreach loop.

So here is what I'm looking for: a way to somehow skip or something the erros and notices and continue with the next folder and file.

Is there a way? Thank's for any help.

Ok so here is the foreach loop:

foreach ($inputFileName as $key => $fileName) {
$objReader = PHPExcel_IOFactory::load($fileName);

$activeSheet = $objReader->getActiveSheet()->toArray(null,false,true,false);

echo "<pre>";
    echo $key;
echo "</pre>";
}

Upvotes: 0

Views: 1570

Answers (2)

Barmar
Barmar

Reputation: 781721

Just a guess:

foreach ($inputFileName as $key => $fileName) {
    $objReader = PHPExcel_IOFactory::load($fileName);

    if ($objReader) {
        $activeSheet = $objReader->getActiveSheet()->toArray(null,false,true,false);

        echo "<pre>";
            echo $key;
        echo "</pre>";
    }
}

It's pretty common for functions to return false when they fail.

Upvotes: 1

Alexandre Nucera
Alexandre Nucera

Reputation: 2223

Maybe you can use the function error_reporting at the beginning of your script to skip notices :

error_reporting(E_ERROR | E_WARNING | E_PARSE);

And set it back to your original value once you are done with your treatment :

error_reporting(-1); //Report all errors

You can find more info here : http://php.net/manual/fr/function.error-reporting.php

Upvotes: 0

Related Questions