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;
Related
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 --------------
I'm trying to download a list of email addresses from a database in WordPress to .CSV.
Anybody point me in the right direction:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
$results = $wpdb->get_results( "SELECT * FROM table");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
$data = json_encode($row);
}
outputCSV($data);
function outputCSV($data) {
$output = fopen("php://output", "w");
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
}
This will do the trick:
header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename="filename.csv"');
header("Pragma: no-cache");
header("Expires: 0");
echo '"Header 1","Header 2","Header 3"'."\n";
$results = $wpdb->get_results("SELECT * FROM `wp_newsletter_signup`");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
echo '"' . $row['column1'] . '","' . $row['column2'] . '","' . $row['column3'] . '"' . "\n";
}
die();
Note my content type of application/vnd.ms-excel I use this as personal preference due to higher support in older windows machines, but you can continue to use text/csv - A list of mime types can be found here http://filext.com/file-extension/CSV
Change
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
$data = json_encode($row);
}
to
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
$data[] = $row;
}
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";
}
Thanks to the users community on this forum, I wrote a very simple web form that allows my user to view text files from within their Internet browser.
I have now two functions whereby the text files returned by the search are compressed into a ZIP. Here's my code
function getFilesFromSite() {
$result = null;
$ZIPresult = null;
if (empty($_POST['DBSite'])) { return null; }
$mydir = MYDIR;
$dir = opendir($mydir);
$DBSite = $_POST['DBSite'];
$getfilename = mysql_query("select filename from search_table where site='" . $DBSite . "'") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
shell_exec("/bin/rm -f SearchResult.zip;/usr/bin/zip -9 SearchResult.zip ". $ZIPresult ." > /dev/null ");
//header for forced download
header("Pragma: public");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$fileName = 'SearchResult.zip';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Transfer-Encoding: binary");
header('Content-type: application/zip');
header("Content-length: " . filesize($fileName));
header('Content-Disposition: attachment; filename="' . $fileName . '"');
ob_start(); // Starts output buffering.
readfile($fileName); // "Outputs" the file.
$content = ob_get_flush(); // Grabs the output and assigns it to a variable.
print base64_encode($content);
}
function getFilesFromError() {
//Just a copy paste from above with different input parameter...
}
The problem is that the ZIP file with the contents from whatever search was done first gets downloaded over and over again. For instance, the results from getFilesFromSite() will always get downloaded even though I did a search with getFilesFromError() afterwards.
I suspect my headers are incorrectly set but I am not sure where.
PS: The new ZipArchive() library/class is not available on our production environment so I chose to use the Unix utility ZIP instead.
Using Base64 was actually not working for reasons well stated here. Instead, I turned zlib compression off and reverted back to using binary as output format. Finally, I set Content-Type to application/octet-stream in my header. Everything is working fine now ; here's my code:
function getFiles() {
ini_set('zlib.output_compression', 'Off');
$result = null;
$ZIPresult = null;
$cleanup = null;
$output = null;
$fileName = null;
//remove old zip if any
$cleanup = shell_exec("/bin/rm -f SearchResult.zip");
error_log("SHELL OUTPUT=>" . $cleanup, 0);
//test
if (empty($_POST['DBRIDs'])) { return null; }
$mydir = MYDIR; // set from the CONSTANT
$dir = opendir($mydir);
$DBRIDs = $_POST['DBRIDs'];
$getfilename = mysql_query("select /*! SQL_CACHE */ filename from automation where rid in (" . $DBRIDs . ")") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
$output = shell_exec("/usr/bin/zip SearchResult.zip ". $ZIPresult ." ");
error_log("SHELL OUTPUT=>" . $output, 0);
$fileName = 'SearchResult.zip';
error_log("ZIP FILENAME=>" . $fileName, 0);
if (file_exists($fileName)) {
//header for forced download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fileName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
ob_clean();
flush();
readfile($fileName);
exit;
}
}
return $result;
}
Thanks to all for taking the time!!
i have a table which shows some mysql data, every entry has a checkbox to select individual entries, now i want to be able to export those selected entries into a xml or txt file, i tried this:
<?php
if ($_POST['exporttxt']) {
for ($i = 0; $i < count($_POST['checkbox']); $i++) {
$export_id = $checkbox[$i];
$sql = "SELECT * FROM table WHERE id='$export_id'";
$result = mysql_query($sql);
}
$output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n";
if ($result->num_rows > 0) {
while ($myrow = $result->fetch_assoc())
{
$output .= "\t<row>\n";
foreach ($myrow as $_name => $_value)
{
$output .= "\t\t<$_name>$_value</$_name>\n";
}
$output .= "\t</row>\n";
}
}
$output .= "</root>";
}
header('content-type: text/xml');
header('content-disposition: attachment; filename=data_export.xml');
echo $output;
exit;
?>
But that didn't work at all, any hints ?
I've changed the code a bit, i am now using this
<?php
if ($_POST['exporttxt']) {
for($i=0;$i<count($_POST['checkbox']);$i++){
$export_id = $checkbox[$i];
$text = mysql_query("SELECT code FROM ticket WHERE id='$export_id'");
$text = mysql_fetch_assoc($text);
$text = $text["code"];
ob_end_flush();
header("Content-type: text/plain");
header("Content-disposition: attachment;filename=\"filename.txt\"");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
echo($text);
}
}
?>
I now get proper output on my screen, but it won't offer me to download the file ?
Your original code was querying each of the checkboxed IDs individually (a long and laborious way to handle it) and was trying to dump the results individually per row (not going to work well for you).
Try this. (NOTE: Untested, but should give you a good starting point to develop.)
if( $_POST['exporttxt'] ){
if( count( $_POST['checkbox'] )>0 ){
// If the checkbox values are meant to all be integers, you might want to perform some validation/sanitisation/filtering here
// Up to you to do that
// Collapse the IDs from the checkboxes into a comma-delimited string
$export_ids = implode( ',' , $_POST['checkbox'] );
// Template the SQL Query
$sqlTpl = 'SELECT code FROM ticket WHERE id IN ( %s )';
// Compile the SQL Query String
$sqlStr = sprintf( $sqlTpl , $export_ids );
// Execute the SQL Query
if( !( $sqlRes = mysql_query( $sqlStr ) ) ){
// SQL Error - Log it, Handle it
}elseif( mysql_num_rows( $sqlRes )==0) {
// No Rows Returned - Log it, Handle it
}else{
// We have results - process them
$text = array();
while( $r = mysql_fetch_assoc( $sqlRes ) ){
// Looping through the returned rows, adding them to the $text array
$text[] = $r['code'];
}
// Collapse the $text array down into a normal string, with one element per line
$output = implode( "\n" , $text );
// Output Handling from #narcisradu's answer
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary;\n");
header("Content-Disposition: attachment; filename=\"filename.txt\";\n");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
echo $output;
die; // Prevent any further output
}
}else{
// No Checkboxes Checked
echo 'You must select one or more checkboxes to export something, muppet.';
}
}
First of all:
for($i=0;$i<count($_POST['checkbox']);$i++){
$export_id = $checkbox[$i];
$sql = "SELECT * FROM table WHERE id='$export_id'";
$result = mysql_query($sql);}
This piece of code will actually do a query for every element in _POST['checkbox'] array but then you are using the result of the last query and you are not parsing the result of every query.
Please make sure the generated XML is well-formed and you actually have some data, by displaying directly into the browser.
After that you may try to force download:
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Transfer-Encoding: binary;\n");
header("Content-Disposition: attachment; filename=\"".urlencode(basename($file_name))."\";\n");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: ".strlen($output).";\n");
ob_end_flush();