Add heading on export using fputcsv php - php

I am trying to export db rows using fputcsv() in csv file. how i can add heading on first, center align then columns then data my code works well without heading. I know there is many api's but is this possible with in my code.
Here is my code:-
Enquiry Report
id name class func
1 rk ba call()
2 bk bd that()
function exportdata_to_excel($details) {
// filename for download
$filename = date("Y-m-d").".csv";
header('Content-Type: text/csv');
header("Content-Disposition: attachment; filename=\"$filename\"");
$out = fopen("php://output", 'w');
$flag = false;
//$result = $orderDetails;
while($row = mysql_fetch_assoc($details)) {
$arr =array('Enquiry id'=>$row['id'],'Date'=>$row['created_on'],'Name'=>$row['name'], 'Email'=>$row['email'], 'Telephone'=>$row['telephone'], 'Customer Request'=>$row['customer_request'], 'Special Request'=>$row['special_request']);
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($arr), ',', '"');
$flag = true;
}
fputcsv($out, array_values($arr), ',', '"');
}
fclose($out);
exit();
}

This worked for me.
function downloadCSV($data)
{
$filename = date("Y-m-d").".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header("Content-Transfer-Encoding: UTF-8");
$f = fopen('php://output', 'a');
fputcsv($f, array_keys($data[0]));
foreach ($data as $row)
{
fputcsv($f, $row);
}
fclose($f);
}

Try this after opening the file, you want to write in e.g. i want to write a file at below path:
$fp = fopen('csvfiles/myfile.csv','w')
You have to enter headers separately, so for this make an array of headers like:
$csv_fields=array();
$csv_fields[] = 'Enquiry id';
$csv_fields[] = 'Date';
$csv_fields[] = 'Name';
$csv_fields[] = 'Email';
$csv_fields[] = 'Telephone';
$csv_fields[] = 'Customer Request';
$csv_fields[] = 'Special Request';
After making headers add these headers to the file.
fputcsv($fp, $csv_fields);
while($row = mysql_fetch_assoc($details)) {
fputcsv($fp,$row);
}
fclose($fp);
Also add following headers on top so that file can be viewed easily:
header("content-type: application/force-download");
header('Content-Type: application/csv');
header('Pragma: no-cache');

Related

Why my CSV file was start filling from the 2nd line?

I am exporting MySQL data successfully to a csv file. But in the csv file first line was empty and data starts from 2nd line. Below is my code.
$delimiter = ";";
$generated_date = date("Y-m-d-H-i-s");
$filename = 'order_detail_report'.$generated_date.".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
$output = fopen('php://output', 'w+');
fputcsv($output, array('Order Type','Order Number','EAN','Article #'),$delimiter);
sql query
<?php
$lineData = array();
$query = "my select query";
$res = mysqli_query($mysqliConn,$query);
while($result= mysqli_fetch_assoc($res))
{
$lineData[] = $result;
fputcsv($output, $lineData, $delimiter);
unset($lineData);
}
Data was exporting successfully to csv but it was starting from 2nd line, any help would be greatly appreciated.
EDIT
<?php
//header info for browser
$delimiter = ";";
$generated_date = date("Y-m-d-H-i-s");
$filename = 'order_detail_report'.$generated_date.".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
$output = fopen('php://output', 'w');
fputcsv($output, array('Order Type','Order Number','EAN','Article #','Title','Amazon Price','ERP Price','Requested Quantity','Dispatch Quantity','Rejected Quantity','Cancelled Quantity','Delivery Date','Status','EDD','LDD','Dispatch Center','Order Received','Price Status','Country'),$delimiter);
?>
I just removed all my mysql related query and only using the above one.

Download multiple .txt files into .zip file with PHP

Now in system it is possible to download .txt file generated from MySQL table row. I am trying to make it possible to download all .txt files in one zip file. Actually, I stuck on the point where I am not sure if my approach is possible.
if (isset($_POST["ExportAll"])) {
$query = $con->query("SELECT id, filename FROM thistable");
$MultiArray = Array();
while($result = $query->fetch_assoc()){
$rowArray = Array();
$rowArray[] = $result['id'];
$rowArray[] = $result['filename'];
$MultiArray[] = $rowArray;
}
foreach ($MultiArray as $arg) {
$query = "SELECT * FROM thistable WHERE id LIKE '" . $arg[0] . "';";
$result = mysqli_query($con, $query);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $arg[1] );
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$output = fopen("php://output", "w");
while ($row = mysqli_fetch_assoc($result)) {
foreach(array_slice($row,2) as $line) {
echo ("$line \r\n");
}
}
fclose($output);
}
}
It is possible to put all $output values into some kind of $zipArray = Array() and then download it with header("Content-type: application/zip");
?
Yes you can download multiple text files as single zip file using php ZipArchive class. This is sample only you can try with your own scenario.
$zipname = 'sample.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
$files_array = ["sample1", "sample2"]; // List of file names
foreach ($files_array as $file) {
$row = ["Line 1", "Line 2", "Line 3", "Line 5"]; // Assuming as your table row
$filename = $file.".txt";
$lines_to_add = "";
foreach(array_slice($row, 2) as $line) {
$lines_to_add .= $line."\r\n";
}
$zip->addFromString($filename, $lines_to_add); // Adding lines to file
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
unlink($zipname); // Remove zip file if you don't want be in server

CodeIgniter: Export data from database into excel and download

I'm working on a project, that requires exporting data from MYSQL DB depending on the multiple conditions. I am referring this:
This is my source code:
public function exportExcelData($records)
{
$heading = false;
if (!empty($records))
foreach ($records as $row) {
if (!$heading) {
// display field/column names as a first row
echo implode("\t", array_keys($row)) . "\n";
$heading = true;
}
echo implode("\t", ($row)) . "\n";
}
}
public function fetchDataFromTable()
{
$query =$this->db->get('one_piece_characters'); // fetch Data from table
$allData = $query->result_array(); // this will return all data into array
$dataToExports = [];
foreach ($allData as $data) {
$arrangeData['Charater Name'] = $data['name'];
$arrangeData['Charater Profile'] = $data['profile'];
$arrangeData['Charater Desc'] = $data['description'];
$dataToExports[] = $arrangeData;
}
// set header
$filename = "dataToExport.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
$this->exportExcelData($dataToExports);
}
If I use it without any where clause, it is giving entire table.
If i use only single where clause, it works good.
Bur, if I use multiple where conditions. it gives me a blank excel sheet.
Does anyone have any idea regarding how to make it work with multiple where conditions?
Try using this code on your model file:
function createcsv(){
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$delimiter = ",";
$newline = "\r\n";
$filename = "filename.csv";
$query = "SELECT * FROM YourTable"; //USE HERE YOUR QUERY
$result = $this->db->query($query);
$data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
force_download($filename, $data);
}
// ecport contect list in csv ,
public function cnt_explode(){
$csvData[] =array( "Name", "Email Id","Mobile No.","Event", "City","location","No of guest","Event Date","Budget",
"Venue Type","Food","Drink","Description","Date");
$data = $this->contact_model->get_contact(NULL);
foreach($data as $cnt){
$csvData[]=array(
$cnt->name ,$cnt->email, $cnt->mobile_no, $cnt->event, $cnt->city, $cnt->location, $cnt->no_guest,$cnt->event_date,$cnt->budget, $cnt->venue_type,
$cnt->food, $cnt->drink, $cnt->description,$cnt->created_on,
);
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=venuexpo_".time().".csv");
header("Content-Transfer-Encoding: binary");
$df = fopen("php://output", 'w');
array_walk($csvData, function($row) use ($df) {
fputcsv($df, $row);
});
fclose($df);
}
///------------ downlode csv done --------------

Pull customer data into all columns in a csv file

This is my current code which pulls all data into a single column. I would like it
to pull data into its own column. Thanks for any help
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
foreach ($query as $k=>$v) {
$_csv_data= $v["email"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["first_name"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["business"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["phone_no"]. "\n";
fwrite( $fp, $_csv_data );
}
foreach ($query as $k=>$v) {
$_csv_data= $v["shipping_address"]. "\n";
fwrite( $fp, $_csv_data );
}
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>
This is my first post on here and I've found all the info here very informative. Thanks for all you do.
EDIT:
Here is the current code with the syntax error
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
# let's get keys into an order that you like
$fields = array('email','first_name','business','phone_no','shipping_address');
foreach ($query as $k=>$v) {
// put the fields for this row into an array
foreach ($fields as $field) {
$data[] = $v[$field];
}
fputcsv($fp, $data);
unset($data);
}
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>
For CSVs, instead of fwrite, you can use fputcsv, you just pass it an array of columns to insert in the row.
$array = array('column one contents', 'column two contents');
fputcsv($fp, $array);
I would suggest looking into fputcsv.
php manual
It looks like your code was looping through all the data, printing out the email. Then looping again and printing out the first_name... I haven't tested it, but this uses fputcsv to write the file - I changed only those parts of the code.
<?php
include('codelibrary/inc/variables.php');
include("session.php");
$obj= new database_class();
$query = $obj->getAnyTableAllData($obj->getTable("var_customer")," and email != '' order by email ");
$filename = 'customer_email.csv';
$fp = fopen($filename, 'w');
# let's get keys into an order that you like
$fields = array('email','first_name','business','phone_no','shipping_address');
foreach ($query as $k=>$v) {
// put the fields for this row into an array
foreach ($fields as $field) {
$data[] = $v[$field];
}
$lines[] = $data; // add the row of data to $lines
unset($data);
}
fputcsv($fp, $lines);
fclose($fp);
if(is_file($filename))
{
$size=filesize("$filename");
header("Content-type: application/csv");
header("Content-Length: $size");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile($filename);
exit;
}
else
{
echo "Invalid file!";
}
?>

Download csv from codeigniter mysql

I think I'm missing something obvious. I'm trying to export a dataset from a MySQL query to CSV without printing it to the browser.
Here's my code:
<?php
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output'); // Read the file's contents
$name = 'data.csv';
force_download($name, $data);
fclose($fp);
?>
$stories is my array created from the MySQL query.
Currently everything prints to the browser with no errors and no download but I would like to force a CSV download. How can I do this?
final working code:
$this->load->helper('download');
$list = $stories;
$fp = fopen('php://output', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
$data = file_get_contents('php://output');
$name = 'data.csv';
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();
force_download($name, $data);
fclose($fp);
You can call model CSV() from your controller as
$this->load->model('Users_model');
$this->Users_model->csv();
and in the model
function csv()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$query = $this->db->query("SELECT * FROM Users");
$delimiter = ",";
$newline = "\r\n";
$data = $this->dbutil->csv_from_result($query, $delimiter, $newline);
force_download('CSV_Report.csv', $data);
}
Your File will start downloading
I can't tell what headers are set from the Codeigniter force_download() function sets. If it is indeed going to the screen I would suspect the necessary headers are missing. You can add the below headers to your code to set correct csv dowload headers (The cache control will ensure fresh data download each time:
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.$name);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
i am use this and its work
header('Content-Type: text/csv; charset=utf-8');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header("Content-Disposition: attachment; filename=backup" . date('y-m-d') . ".csv");
header('Last-Modified: ' . date('D M j G:i:s T Y'));
$outss = fopen("php://output", "w");
$this->db->order_by('ID', 'DESC');
$query = $this->db->get('urls');
foreach ($query->result_array() as $rows) {
fputcsv($outss, $rows);
}
fclose($outss);
return;
If you are trying to generate reports in csv format then it will quite easy with codeigniter.
Place this code in your Controller
function get_report()
{
$this->load->model('Main_Model');
$this->load->dbutil();
$this->load->helper('file');
/* get the object */
$report = $this->Main_Model->print_report();
$delimiter = ",";
$newline = "\r\n";
$new_report = $this->dbutil->csv_from_result($report, $delimiter, $newline);
write_file( 'application/third_party/file.csv', $new_report);
$this->load->view('report_success.php');
}
Put this code into Model
public function print_report()
{
return $query = $this->db->query("SELECT * FROM Table_name");
}
report_success.php is just Successful Notification.
Your Report is being Exported. Thank you
Finally Your "file.csv" is generated.
its basically stored at physical storage.
In CodeIgniter/application/third-party/file.csv
it works.
it will help you.
Here we have sample result set from MySQL and want to export in CSV file.
Step 1: Get MySql data in key value pair.
$data = array(
'0' => array('Name'=> 'Parvez', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
'1' => array('Name'=> 'Alam', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
'2' => array('Name'=> 'Sunnay', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
'3' => array('Name'=> 'Amir', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
'4' => array('Name'=> 'Amir1', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
'5' => array('Name'=> 'Amir2', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
);
Step 2: PHP code to get options type and force to browser download file instead of display.
if(isset($_POST["ExportType"]))
{
switch($_POST["ExportType"])
{
case "export-to-csv" :
// Submission from
$filename = $_POST["ExportType"] . ".csv";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
ExportCSVFile($data);
//$_POST["ExportType"] = '';
exit();
default :
die("Unknown action : ".$_POST["action"]);
break;
}
}
function ExportCSVFile($records) {
// create a file pointer connected to the output stream
$fh = fopen( 'php://output', 'w' );
$heading = false;
if(!empty($records))
foreach($records as $row) {
if(!$heading) {
// output the column headings
fputcsv($fh, array_keys($row));
$heading = true;
}
// loop over the rows, outputting them
fputcsv($fh, array_values($row));
}
fclose($fh);
}
Step 3: Define html layout for display data in table and button to fire export-to-csv action.
<div>Export to csv</div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" id="export-form">
<input type="hidden" value='' id='hidden-type' name='ExportType'/>
</form>
<table id="" class="table table-striped table-bordered">
<tr>
<th>Name</th>
<th>Status</th>
<th>Priority</th>
<th>Salary</th>
</tr>
<tbody>
<?php foreach($data as $row):?>
<tr>
<td><?php echo $row ['Name']?></td>
<td><?php echo $row ['Status']?></td>
<td><?php echo $row ['Priority']?></td>
<td><?php echo $row ['Salary']?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Step 3: Now we will use jQuery code to get click event.
<script type="text/javascript">
$(document).ready(function() {
jQuery('#export-to-csv').bind("click", function() {
var target = $(this).attr('id');
switch(target) {
case 'export-to-csv' :
$('#hidden-type').val(target);
//alert($('#hidden-type').val());
$('#export-form').submit();
$('#hidden-type').val('');
break
}
});
});
</script>

Categories