Tuesday 1 January 2013

Download/get data into excel file using php



<?php
//your code for to create your sql statement, we'll call it $query...

 $query="SELECT `candidate_id`, `fullname`,`email`,`alternate_email`, `location`, `mobile`, `landline`, `expyear`, `expmonth`, `keyskill`, `headlineprofile`, `currcmp`, `fuctionalarea`, `basicedu`, `masteredu`, `docedu`, `create_date`, `current_salary`, `current_industry`, `date_of_birth`, `gender`, `marital_status`, `address`,  `city`, `country`, `pincode`,`specialization`, `university`, `edu_year`, `role` FROM `candidate_reg`";


//get the data that we need...

$Result=mysql_query($query);


//fetching each row as an array and placing it into a holder array ($aData)

while($row = mysql_fetch_assoc($Result)){
 $aData[] = $row;
}


//feed the final array to our formatting function...

$contents = getExcelData($aData);

$filename = "myExcelFile.xls";


//code for Save/Open dialog box...

header ("Content-type: application/octet-stream");
header ("Content-Disposition: attachment; filename=".$filename);


//setting the cache expiration to 30 seconds ahead of current time. an IE 8 issue when opening the data directly in the browser without first saving it to a file

$expiredate = time() + 30;
$expireheader = "Expires: ".gmdate("D, d M Y G:i:s",$expiredate)." GMT";
header ($expireheader);


//final output in contents

echo $contents;
exit;
?>

<?php
 function getExcelData($data){
    $retval = "";
    if (is_array($data)  && !empty($data))
    {
     $row = 0;
     foreach(array_values($data) as $_data){
      if (is_array($_data) && !empty($_data))
      {
          if ($row == 0)
          {
              // write the column headers
              $retval = implode("\t",array_keys($_data));
              $retval .= "\n";
          }
           //create a line of values for this row...
              $retval .= implode("\t",array_values($_data));
              $retval .= "\n";
              //increment the row so we don't create headers all over again
              $row++;
       }
     }
    }
  return $retval;
 }
?>

No comments:

Post a Comment