0

I have a database table where except the id column all other columns have comma separated values. I am trying to download the data related to the id, so I used the following code:

view:

<a href="<?php echo base_url('admin_works/downloadexcel/'.$val['id']);?>"  style="margin-left:7%">
    <i class="fa fa-file-excel-o" aria-hidden="true" style="color:green"></i>
</a>

controller:

public function downloadexcel(){
    $this->load->helper('file');
    $this->load->helper('download');
    // file name
    $filename = 'users_'.date('Ymd').'.csv';
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-Type: application/csv; ");

    // get data

    $eid = $this->uri->segment(3);
    $response = $this->db->where("id", $eid)->get('tbl_plans')->result();

    // file creation
    $file = fopen('php://output', 'w');

    $header = array("Table ID","Date","Topic","Name","Client ID","Type","Reference","Status","Assigned","Image URL","Remarks","Captions");
    fputcsv($file, $header);

    foreach ($response as $val){
       $s1=explode(',',$val->ddate);
       $s2=explode(',',$val->details);
       $s3=explode(',',$val->type);
       $s4=explode(',',$val->ref);
       $s5=explode(',',$val->status);
       $s6=explode(',',$val->assign);
       $s7=explode(',',$val->imageurl);
       $s8=explode(',',$val->remarks);
       $s9=explode(',',$val->captions);

       for($i=1;$i<10;$i++){
             for($j=1;$j<10;$j++){
                 $var = 's'.$j;
                 $newArr[] = $$var[$i]??'';
             }
             fputcsv($file,$newArr);
         }
   }
    fclose($file);
    exit;
}

however this gives me a blank file, what is wrong with my code?

Vickel
  • 7,879
  • 6
  • 35
  • 56
ZNO
  • 181
  • 1
  • 10
  • Does this answer your question? [Export to CSV via PHP](https://stackoverflow.com/questions/4249432/export-to-csv-via-php) – Vickel Nov 02 '22 at 13:07

1 Answers1

2
for($i=0;$i<count($s1);$i++){
 $newArr=[];
 for($j=1;$j<12;$j++){
   $var = 's'.$j;
   $newArr[] = $$var[$i]??'';
 }
 fputcsv($file,$newArr);
 }
soma
  • 176
  • 9
  • 1
    I am not sure which I have a greater distaste for: 1. variable variables or 2. code-only answers on Stack Overflow. – mickmackusa Nov 03 '22 at 00:30