I want to export data of a sql table in csv. I am using the follwoing code :
<?php
if(isset($_POST['export']))
{
$file = 'email_csv'; // ?? not defined in original code
$results = $wpdb->get_results("SELECT * FROM `scholarship_uesr`;",ARRAY_A);
if (empty($results)) {
return;
}
$csv_output = '"'.implode('";"',array_keys($results[0])).'";'."\n";;
foreach ($results as $row) {
$csv_output .= '"'.implode('";"',$row).'";'."\n";
}
$csv_output .= "\n";
$dir = "/home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/csv/";
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
// echo "<div class='alert alert-info'>Data Written to CSV File. <a href='".$geturl."' download>Click Here to Download</a></div>";
}
$allsubs = "SELECT * FROM `scholarship_uesr`";
$select_query = $wpdb->get_results($allsubs);
//echo $wpdb->last_error;
?>
<form method="post" action="#" enctype="multipart/form-data">
<input type="submit" name="export" class='btn btn-danger' value="Export Data to CSV !!!">
</form>
When I am using to this code then it is directly print the data of database instead of downloading the file.
When i turn on the error_reporting then it is throwing error :
Warning: Cannot modify header information - headers already sent by (output started at /home/modifoun/public_html/wp-admin/includes/template.php:2041) in /home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/student_list.php on line 45
Warning: Cannot modify header information - headers already sent by (output started at /home/modifoun/public_html/wp-admin/includes/template.php:2041) in /home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/student_list.php on line 46
Warning: Cannot modify header information - headers already sent by (output started at /home/modifoun/public_html/wp-admin/includes/template.php:2041) in /home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/student_list.php on line 47
How can I export data to csv using wordpress
You need to run this before output has started. It looks like you have this in your template file?
Try adding this to your functions.php file.
add_action('init', 'exportCsv');
function exportCsv() {
if(isset($_POST['export']))
{
$file = 'email_csv'; // ?? not defined in original code
$results = $wpdb->get_results("SELECT * FROM `scholarship_uesr`;",ARRAY_A);
if (empty($results)) {
return;
}
$csv_output = '"'.implode('";"',array_keys($results[0])).'";'."\n";;
foreach ($results as $row) {
$csv_output .= '"'.implode('";"',$row).'";'."\n";
}
$csv_output .= "\n";
$dir = "/home/modifoun/public_html/wp-content/plugins/schloarship/menu-pages/csv/";
$filename = $file."_".date("Y-m-d_H-i",time()).".csv";
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
// echo "<div class='alert alert-info'>Data Written to CSV File. <a href='".$geturl."' download>Click Here to Download</a></div>";
}
}
The only thing is required is ob_start() and ob_end_clean()
Just after if(isset($_POST['export'])) use ob_start() and just before the closing braces of this if statement use ob_end_clean().
use below headers
header('Content-Description: File Transfer');
header("Content-Type: application/csv") ;
header("Content-Disposition: attachment; filename=Report.csv");
header("Pragma: no-cache");
header("Expires: 0");
Related
Error Message while opening the file
Second error message when trying to update the file...
Code in PHP
<?php
$filename = "test.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
echo implode("\t", ["Username", "Order Number"]) . "\n";
echo implode("\t", ["wswswsw#s.com", "1234454542122232"]) . "\n";
exit();
?>
Am I missing anything?
This code may be able to assist you in finding a solution to your issue. If it doesn't work as expected, there may be other options that you can try.
<?php
$filename = "test.xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
// Generate the data for the file
$data = [
["Username", "Order Number"],
["wswswsw#s.com", "1234454542122232"]
];
// Use a loop to generate the rows of the file
foreach ($data as $row) {
// Use implode() to concatenate the values in the row into a single string
echo implode("\t", $row) . "\n";
}
exit();
?>
I am able to download a file in csv format for my table , but how to add column headers to the same file .
The current code is following -
// load wpdb
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
$table = $_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $wpdb->prefix$table",ARRAY_A );
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;
I was able to do it by first getting column names and then assigning it to final output :
$table_name = $wpdb->prefix.$_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $table_name",ARRAY_A );
// get column names
$query = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='".$wpdb->dbname."' AND `TABLE_NAME`='".$table_name."'";
$columnNamesList = $wpdb->get_results($query);
foreach ( $columnNamesList as $column_name ) {
$csv_output.=$column_name->COLUMN_NAME.",";
}
// remove last additional comma
$csv_output = substr($csv_output,0,strlen($csv_output)-1);
// start dumping csv rows in new line
$csv_output.="\n";
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;
I'm using following headers to generate excel file from database MySQL using PHP
header("Content-type: application/octet-stream");
header("Content-Type: application/vnd-ms-excel");
header("Content-disposition: attachments;filename=xxx.xls");
in localhost the output is xxx.xls which is correct file but in the server side i am getting xxx.php file (i am using a cpanel account for ftp)
guys please help me with a solution
simply use
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="file.xls"');
Simply you can use the following php code.
You have to give an array with key value pair
$data = array("Name"=> "foo", "age" => 25);
$filename = "My File Name" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($data as $row) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
foreach ($row as $value){
echo $value;
echo "\t";
}
echo "\n";
}
exit;
I'm writing PHP array data to the excel file using some library. When I write the data to the excel file and echo some success message, it works fine. No other data than the intended array gets added to the file.
But when I use headers to make the download of same file functionality workable some additional information present on page (like header menu, some heading, copyright line at bottom of page, etc.)gets added to the file. How to avoid adding this extra information to the excel file? Following is my code:
<?php
require_once( CORE_PATH."/libs/excelwriter.inc.php" );
$objRebateReports = new RebateReports();
if($_POST['btnDownload']!='') {
$rebate_ret = $objRebateReports->GetRebateReport($_POST);
$rebate_data = $objRebateReports->GetResponse();
$t=time();
$fileName = ADMIN_ROOT."modules/rebates/rebate_report_".$t.".xls";
$excel = new ExcelWriter($fileName);
if($excel==false) {
echo $excel->error;
die;
}
$myArr = array('Sr. No.', 'Product','Manufacturer','User Name','Date','Status','Transaction Date');
$excel->writeLine($myArr, array('text-align'=>'center', 'color'=> 'red'));
$id=1;
foreach ($rebate_data as $value) {
$temp_rebate_data =array();
$temp_rebate_data['id'] = $id;
$temp_rebate_data['product'] = "";
$temp_rebate_data['manufacturer'] = "";
$temp_rebate_data['user_name'] = $value['customer_first_name']."".$value['customer_last_name'];
$temp_rebate_data['date'] = $value['created_at'];
$temp_rebate_data['status'] = $value['request_status'];
$temp_rebate_data['transaction_date'] = "";
$row = $temp_rebate_data;
$excel->writeLine($row, array());
$id++;
}
$excel->close();
//Following is the header information in order to download the excel file
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=".$fileName);
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
//Below is the success message after printing the data successfully to the file
//echo "Data written to file $fileName Successfully.";
}
?>
You should use output buffering for this.
//start of the page
ob_start();
//ur code
//headers
ob_clean();
flush();
readfile($file);
exit;
I think this will solve your problem
I am working on export excel data to using php
but it has problem on downloaded as csv with comma separated values
but i need XLS file with table field values
I using the below code
$values = mysql_query("SELECT * FROM $table");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i-1;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
$rown=0;
while( $row = mysql_fetch_assoc($values)){
if($rown++==0)
$csv_output.=implode(";",array_keys($row)."\n";
$csv_output.=implode(";",array_values($row)."\n";
}