PHP : Excel cannot open the file because the file format or file extension is not valid

Viewed 4371

When I try to openning a xls file which I downloading from my application, I have this error :

excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

this is my php code : at first, I upload the xls file :

if (is_uploaded_file($_FILES["file_name"]["tmp_name"])) {
   if (rename($_FILES["file_name"]["tmp_name"], $directoryDestination.$nameDestination))        {
      import::importFile($link,$directoryDestination.$nameDestination, $importLib, $excelName,$enddate);
    $_SESSION['message'] = "ok";
}else{
    $_SESSION['erreur'] = "Error";
}

then in my function :

use PhpOffice\PhpSpreadsheet\IOFactory;

importFile($link,$filename, $importLib, $excelName,$enddate){
header('Content-Type: text/html; charset=utf-8');
    // loading Excel file
    $objPHPExcel = IOFactory::load($filename);
    ....
    database 
    ....
    // copy the file
    mkdir($new_path,0777);
    chmod($new_path, 0777);
    copy($filename,$new_path.$excelName);
    unlink($filename);

// then , in other file, I try to download the file
$contents = file_get_contents($filepath);
$mime = mime_content_type($filepath);
$size = filesize($filepath);
$parts = explode("/", $file);
$filename = end($parts);

header("Content-Type: {$mime}");
header("Content-disposition: attachment; filename=\"" . basename($filename) . "\"");
header("Content-Length: {$size}");
print($contents);
exit();

I'm using MS 2016 (PhpOffice\PhpSpreadsheet). I already tried to change the file extension or to repar it but its not worked

1 Answers

Thanks @Danny Battison When I opened the file with Notpad I saw blanks on the top of the file, so I added ob_end_clean() (doc) just before :

ob_end_clean();
header("Content-Type: {$mime}");

And its works fine.

Related