Saturday 5 April 2014

How to Download CSV File in PHP

CSV stands for Comma Separated Values. This file format is commonly used to store data, export data from database etc.
Let’s create a CSV with more values. Now we are creating CSV with following header and multiple records.





<?php
 $db_host="localhost";
 $db_username="username";
 $db_password="password";
 $db_name="database name";
 
   $conn = mysql_connect($db_host,$db_username,$db_password) or die("Could not connect to Server" .mysql_error());
   mysql_select_db($db_name) or die("Could not connect to Database" .mysql_error());

  $all_members ="SELECT * FROM `csv_table`";
  $all_memb = mysql_query($all_members); 

  $delimiter = ","; // Comma separated

 // File name is kc_csvdemo.csv
 $filename = "kc_csvdemo.csv";

 $data = array('Id', 'Name', 'Qualification','PhoneNumber');
 $string = implode($delimiter, $data);

 print  $string . "\r\n";

 header("Content-type: application/octet-stream");
 header("Content-Disposition: attachment; filename=$filename");
 header("Pragma: no-cache");
 header("Expires: 0");

 // Getting data 
    while($info = mysql_fetch_array( $all_memb )) 
                 {   
        $emp_data['id'] = $info['id'];
                      $emp_data['name'] = $info['name'];
                      $emp_data['branch'] = $info['qualification'];
                      $emp_data['unique_id'] = $info['phonenumber'];
        $dataRowString = implode($delimiter, $emp_data);
                      print $dataRowString . "\r\n";
    
  } 
   exit();
?>
header(‘Content-Disposition: attachment; filename=$filename’);
This header tells the browser that this file should be download with a filename we mention instead of displaying on browser.

No comments:

Post a Comment