I have written a simple php script for download excel file which contain some MySQL data fetching by a MySQL query. Data is coming correctly but when I am printing that result in excel file, all fields are coming in the first column of excel file, which is not correct. I want single field in single column. what I am missing in the code. Please If anyone have any idea how to achieve that. Here is my code -
include('db_connect.php');
$select = "select `dp_id`,`client_id`,`invester_name`,`pan_no` from
(SELECT `dp_id` , `client_id` , `invester_name` , `pan_no`
FROM `app_form` union all
SELECT `dp_id`,`client_id`,`first_holder_name`,`first_holder_pan` FROM `response_record`)
tbl order by `dp_id`,`client_id`";
//run mysql query and then count number of fields
$export = mysql_query ( $select )
or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
//create csv header row, to contain table headers
//with database field names
for ( $i = 0; $i < $fields; $i++ ) {
$header .= mysql_field_name( $export , $i ) . ",";
}
//this is where most of the work is done.
//Loop through the query results, and create
//a row for each
while( $row = mysql_fetch_row( $export ) ) {
$line = '';
//for each field in the row
foreach( $row as $value ) {
//if null, create blank field
if ( ( !isset( $value ) ) || ( $value == "" ) ){
$value = ",";
}
//else, assign field value to our data
else {
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . ",";
}
//add this field value to our row
$line .= $value;
}
//trim whitespace from each row
$data .= trim( $line ) . "\n";
}
//remove all carriage returns from the data
$data = str_replace( "\r" , "" , $data );
$file_name = 'excel_data';
//create a file and send to browser for user to download
header("Content-type: application/vnd.ms-excel");
header( "Content-disposition: filename=".$file_name.".xls");
print "$header\n$data";
exit;
Here is the screen shot of excel file which I am getting after running this script-
Replace following part of your code:
With :
and check it works for me
What about create a .csv file? You can use the function
fputcsv()
from PHP to help you. A comma-separated values (CSV) (or character-separated values) file stores tabular data (numbers and text) in plain-text form. It is relatively simple to use and works great with Excel.As an example of code, you could do this:
References:
fputcsv() - http://php.net/manual/en/function.fputcsv.php
The Comma Separated Value (CSV) File Format - http://creativyst.com/Doc/Articles/CSV/CSV01.htm
Try with this change :