0

I am trying to export few data in CSV file. Though the file is successfully downloaded as well as stored in particular path. If I opened downloaded file from the browser, file showing empty results I don't know where I made mistake please help me out

My Controller

public function export_webdata($p_id,$inptid){
    $project = $this->Lead_Model->get_project_single($p_id);
    $filename = $project[0]->p_name.'_WebsiteInfo_'.time().'.csv';
    $path = getcwd().'/public/files/'.$project[0]->p_name.'/';
    if (!file_exists($path)){
        mkdir($path, 0777, true);
    }
    
    header('Content-Type: text/csv; charset=utf-8');  
    header('Content-Disposition: attachment; filename="'.$filename.'";'); 
    
    $output = fopen($path.$filename, 'w');
    $header = array("Company","Country","Website");
    fputcsv($output, $header);
    $extdata = $this->Lead_Model->webdata_export($inptid);
    
    foreach ($extdata as $key=>$line){
        fputcsv($output,$line);
    }
    fclose($output);
}

My Model

public function webdata_export($inptid)
{
    $response = array();
    $db5 = $this->load->database('output_db', TRUE);
    $q = $db5->select('Company,Country,Website')->get_where('website_info', ['input_id' => $inptid, 'type_id' => 2,'uploaded_by' => $this->session->admin_id]);
    $response = $q->result_array();
    return $response;  
}
Jackson
  • 33
  • 7
  • What have you tried to resolve the problem? Where are you stuck? I don't see any code that **downloads** anything - the part in `export_webdata` solely prints these headers, and writes a file to the server – Nico Haase Dec 02 '21 at 16:43
  • Maybe https://stackoverflow.com/questions/4249432/export-to-csv-via-php helps? – Nico Haase Dec 02 '21 at 16:47
  • 1
    Or this? https://stackoverflow.com/questions/20840274/download-csv-from-codeigniter-mysql (mind the paths used in `fopen`!) – Nico Haase Dec 02 '21 at 16:48
  • 1
    Did you check any of the other links posted above? – Nico Haase Dec 07 '21 at 16:04
  • @Nico Haase - I checked with your second link, Working fine now thanks a lot – Jackson Dec 09 '21 at 13:14

1 Answers1

0

you need to add below code to clean buffer before or after header

 header('Content-Type: text/csv; charset=utf-8');  
 header('Content-Disposition: attachment; filename="'.$filename.'";'); 
 while ( ob_get_level() ) {
  ob_end_clean();
}
Vijay Maurya
  • 349
  • 4
  • 11
  • Please share more details such that others can learn from your answer. What did you change, and why? – Nico Haase Dec 02 '21 at 16:43
  • @Nico Haase When I click on export button blank CSV file will downloaded from browser and I don't know where I need to add download code as you mention – Jackson Dec 06 '21 at 20:08
  • @Vijay Maurya I tried with your code but still blank file is downloading – Jackson Dec 07 '21 at 15:57