PHP to excel.xlsx fopen() gives error - excel cannot open because file format or file extension is not valid - avoiding extternal library

Viewed 36

After numerous attempts i have finally given in.

I am trying download an excel file when user clicks export without any external libraries (preferably) :

so in my jscript

$.ajax{(
      url:url,
      data:{action:export},
      success:function(response){
              response = JSON.parse(response);
              location = window.location + '?download.php=' + response.file;
      }
)};

server side after receiving request and check through it , generates an output array which is $d_out in this case:

  $output = '';

  $column_done = false;

  foreach( $d_out as $listing ){
    
    if( ! $column_done ){
        
        $output.= implode( "\t" , array_keys( $listing ) ) . "\n";
        
        $column_done = true;
    }
    
    $output.= implode( "\t" , array_values( $listing ) ) . "\n";
  }

  //out put to file

  $file_name = 'export_data_' . date('Ymd') . ".xlsx"; 

  $file_path = $_SERVER['DOCUMENT_ROOT'] . '/path/tempfolder/';

  $file_open = fopen( $file_path . $file_name , 'w' );

if( $file_open ){
    
    fwrite( $file_open , $output );
    
    fclose( $file_open );

    return $this->data_out = [ 'success' => true , 'file'  => $file_name ] ;
    
}else{
    
    return $this->data_out = [ 'success' => false , 'error' => 'Could not export file' ];
}

at this point the file is sitting in the 'tempfolder' awaiting download.

and now finally in my download.php

$file_name = $_GET['download'];

$file_path = $_SERVER['DOCUMENT_ROOT'] . '/path/tempfolder/';

if( file_exists(  $file_path . $file_name  ) ){
    
    // Headers for download

    header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header("Content-Disposition: attachment; filename=\"" . $file_name ." \"");
    header('Content-Length: ' . filesize( $file_path . $file_name ) );

    readfile( $file_path . $file_name );

    unlink( $file_path . $file_name );
}

exit();

everything works in terms of writing to file and download, i still get the prompt when i open the file in excel. I have also tried to download a blank file from the server and it the prompt persists.

WHAT GIVES!!

All help is appreciated. Thanks in advance!

0 Answers
Related