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;
}
My Answer:
>project_model->get_project($p_id);
$data['webdata'] = $this->webdata_model->get_webdata($p_id, $inptid);
$this->load->helper('csv');
$file_name = 'webdata_' . $project->name . '.csv';
$file_path = FCPATH . 'exports/' . $file_name;
$csv_data = array();
foreach ($data['webdata'] as $row) {
$csv_data[] = array(
$row->id,
$row->name,
$row->url,
$row->description
);
}
array_to_csv($csv_data, $file_path);
// Force download the file
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
readfile($file_path);
}
Make sure you have the `array_to_csv` function in your helper file. Also, check if the data is being fetched correctly from the database and stored in the CSV file. If the file is empty, there might be an issue with the data retrieval or formatting.
Rate this post
4 of 5 based on 7174 votesComments