Export data into CSV file using PHP

If you want to export data from mysql or any other database using php. Then first time its looking very complex but here you can find easy solution of every complex looking problem.

What do you need :

You need to arrange your data into array in key value combination. like below screne shot format  -


Explain :  In the above screne shot Index (Student, Net Fees, Total Payments, Balance Due, Current Month, Last Payment) will be display the heading into CSV.


Below Is My Functions:
 

 // This Function Is Used To Write Csv File.
 function array2csv(array &$array)
 {
    if (count($array) == 0) {
   return null;
    }
    $df = fopen("php://output", 'w');
    fputcsv($df, array_keys(reset($array)));
    foreach ($array as $row) {
    fputcsv($df, $row);
    }
    fclose($df);
 }

 
 // This Function Is Used To Force Download The File.
 function forceDownload($filename) 
  {
      $now = date("D, d M Y H:i:s");
      header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
      header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
      header("Last-Modified: {$now} GMT");
        // force download  
      header("Content-Type: application/force-download");
      header("Content-Type: application/octet-stream");
      header("Content-Type: application/download");
      // disposition / encoding on response body
      header("Content-Disposition: attachment;filename={$filename}");
      header("Content-Transfer-Encoding: binary");
  } 

 
Method Of Uses : You just need to pass your array into this function and rest of 
work it do its self.
 
Calling of function : 
 
<?php
 
//Suppose my above screne shot data is stored into $newArr.

forceDownload("Fee&discountReport_" . date("Y-m-d") . ".csv");
echo array2csv($newArr);
die();
 
?>
 
 
Your csv will be look something like below screneshot: 
 
 
 
 
If you like this post please don't forget to leave a comment.
 
Chears 
Happy Coding :) 
 

Post a Comment

Previous Post Next Post