Search code examples
phpzipphpexcelphp-extension

PhpExcel Reader: Couldn't read certain files


Error Shows ->Warning: ZipArchive::getFromName(): Invalid or unitialized Zip object

When uploading files, and reading excel files, sometimes it shows that error message.

This is my code:

$pasFile    = $_FILES['inputFileLocation']['name'];
$target_path    = basename($pasFile);
if(move_uploaded_file($_FILES["inputFileLocation"]["tmp_name"], $target_path)){
        require_once '../template/PHPExcel/Classes/PHPExcel.php';
        $objReader = PHPExcel_IOFactory::createReader('Excel2007');
        $worksheet_names = $objReader->listWorksheetNames($pasFile);
        $countWorksheet = count($worksheet_names);
        $optionSheetName = "<option></option>";
        for($x = 0;$x < $countWorksheet;$x++){
            $optionSheetName = $optionSheetName."<option value='".$worksheet_names[$x]."'>".$worksheet_names[$x]."</option>";
        }
    }

Thank you in advance! :)


Solution

  • My mistake! The file that I was uploading had different types of excel format.

    This code now works by identifying the format then passing it to the create reader. Many thanks to Mr. Baker! I added this codes:

        $inputFileType = PHPExcel_IOFactory::identify($pasFile);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    

    Resulting to this one:

    $pasFile    = $_FILES['inputFileLocation']['name'];
    $target_path    = basename($pasFile);
    if(move_uploaded_file($_FILES["inputFileLocation"]["tmp_name"], $target_path)){
            require_once '../template/PHPExcel/Classes/PHPExcel.php';
            $inputFileType = PHPExcel_IOFactory::identify($pasFile);
            $objReader = PHPExcel_IOFactory::createReader($inputFileType);
            $worksheet_names = $objReader->listWorksheetNames($pasFile);
            $countWorksheet = count($worksheet_names);
            $optionSheetName = "<option></option>";
            for($x = 0;$x < $countWorksheet;$x++){
                $optionSheetName = $optionSheetName."<option value='".$worksheet_names[$x]."'>".$worksheet_names[$x]."</option>";
            }
        }
    

    identify() first before createReader()...