Export Excel from Mysql Table - php

Pls, let someone help me with this code, When I export, it export the file but start with row2, the first row is excluded.it reads like , header, then row2,3,4 till the end of the row.
<?php
require_once("/includes/session.php");
require_once("/includes/db_connection.php");
require_once("/includes/functions.php");
// Table Name that you want
// to export in csv
$ShowTable = "staff_tab";
$today=date("dmY");
$FileName = "StaffRecord".$today.". csv";
$file = fopen($FileName,"w");
$sql = mysqli_query($connection,("SELECT * FROM $ShowTable LIMIT 500"));
$row = mysqli_fetch_assoc($sql);
// Save headings alon
$HeadingsArray=array();
foreach($row as $name => $value){
$HeadingsArray[]=$name;
}
fputcsv($file,$HeadingsArray);
// Save all records without headings
while($row = mysqli_fetch_assoc($sql)){
$valuesArray=array();
foreach($row as $name => $value){
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
}
fclose($file);
header("Location: $FileName");
echo "Complete Record saves as CSV in file: <b style=\"color:red;\">$FileName</b>";
?>

Your call to $row = mysqli_fetch_assoc($sql); is pushing the internal pointer forward to row 2. Use mysqli_data_seek($sql, 0); to push it back to the start. http://php.net/manual/en/function.mysql-data-seek.php
...
$sql = mysqli_query($connection,("SELECT * FROM $ShowTable LIMIT 500"));
$row = mysqli_fetch_assoc($sql);
mysqli_data_seek($sql, 0); // return pointer to first row
// Save headings alon
$HeadingsArray=array();
...

maybe this could help as this will include all rows and set headers from the db headers. This would also force download the file without leaving the page.
$export = mysqli_query ($query) or die ( "Sql error : " . mysqli_error( ) );
// extract the field names for header
$fields = mysqli_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$headers = mysqli_fetch_field($export);
$header .= $headers->name. "\t";
}
// export data
while( $row = mysqli_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\nNo Record(s) Found!\n";
}
// allow exported file to download forcefully
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Something.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

Related

CSV Download not working for all pages

I have a website that I created for reports. There are basically 3 reports. I have a button on each page that calls another PHP page that will download the results of the query that fills the page into a CSV file. This works fine on one page, but on the other two it gives me an error when trying to open. It says:
The file format and extension of 'FileName' don't match. the file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?
I click yes, then get this:
Excel has detected that 'FileName' is a SYLK file, but cannot load it. Either the file has errors or it is not a SYLK file format. Click OK to try to open the file in a different format.
I click OK and it opens fine.
Where as on the other page it just opens.
Here's most of the ExportToExcel.php
switch ($_POST['ExportToExcel'])
{
case "QDef":
$tsql = "select Id,QSrc,QName,QDef,isActive,RunReport,FilePath from pmdb.v_QDefs order by Id";
$hsql = "select Headings from TableHeadings where TableName = 'v_QDefs' and Headings != 'Edit' order by ID";
break;
case "TableUpdates":
$tsql = "select ID, TableName, UpdateDate from pmdb.TableUpdates order by UpdateDate";
$hsql = "select Headings from TableHeadings where TableName = 'TableUpdates' and Headings != 'Edit' order by ID";
break;
}
$filename = $_POST['ExportToExcel'];
header("Content-Type: application/x-csv");
header("Content-Disposition: attachment; filename=$filename.csv");
//define separators (defines columns in excel)
$sep = ",";
$br = "\r\n"; //line break
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$headings = array();
$NumHeadings = count($rHeadings);
for ($i = 0;$i < $NumHeadings; $i++)
{
$headings[] = $rHeadings[$i]["Headings"];
}
//start of printing column names as names of SQL fields
foreach($headings as $Heading => $value)
{
echo "$value" . $sep;
}
//end of printing column names
echo $br; //separate the headers and the data
foreach($conn->query($tsql) as $row)
{
for ($i = 0;$i < $NumHeadings;$i++)
{
$CommentPos = strpos($rHeadings[$i]["Headings"],"comment");
$NewLines = array("\r\n","\n\r","\n","\r");
$UseValue = str_replace($NewLines, " ",$row[$i]);
$UseValue = str_replace('"', "'",$row[$i]);
$pos = strpos($UseValue,",");
if ($CommentPos === FALSE || $pos === FALSE || isset($UseValue))
{
echo '"' . $UseValue . '"' . $sep;
}
else
{
echo $UseValue . $sep . "Not quoted";
}
}
echo $br;
}
I have a include at the top that has the connection string for connecting to my MSSQL DB, which does work, or there'd be nothing displayed on the page to begin with.
I just con't figure out why the page doesn't work the same way for all reports when they are all calling the page the same way.
EDIT again
I tried several ideas from below and now I have this:
$filename = $_POST['ExportToExcel'] . '.csv';
$Opened = fopen($filename,'w');
header("Content-Type: text/csv; charset=utf-8'");
header("Content-Disposition: attachment; filename=$filename");
fputcsv($Opened,$headings);
foreach($conn->query($tsql) as $row)
{
fputcsv($Opened,$row);
}
fclose($Opened);
Which still gives me a blank spreadsheet. So obviously I'm still doing something wrong?
Nevermind, I updated the Headings for all the tables that I am trying to export so that the first column is no longer ID, but is instead Id. Since it's no longer all caps it is working fine without the fputcsv since that isn't doing anything for me anyhow.
$filename = $_POST['ExportToExcel'] . '.csv';
header("Content-Type: text/csv; charset=utf-8'");
header("Content-Disposition: attachment; filename=$filename");
//define separators (defines columns in excel)
$sep = ",";
$br = "\r\n"; //line break
$getHeadings = $conn->query($hsql);
$rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
$headings = array();
$NumHeadings = count($rHeadings);
for ($i = 0;$i < $NumHeadings; $i++)
{
$headings[] = $rHeadings[$i]["Headings"];
}
//start of printing column names as names of SQL fields
foreach($headings as $Heading => $value)
{
echo "$value" . $sep;
}
foreach($conn->query($tsql) as $row)
{
for ($i = 0;$i < $NumHeadings;$i++)
{
$CommentPos = strpos($rHeadings[$i]["Headings"],"comment");
$NewLines = array("\r\n","\n\r","\n","\r");
$UseValue = str_replace($NewLines, " ",$row[$i]);
$UseValue = str_replace('"', "'",$row[$i]);
$pos = strpos($UseValue,",");
if ($CommentPos === FALSE || $pos === FALSE || isset($UseValue))
{
echo '"' . $UseValue . '"' . $sep;
}
else
{
echo $UseValue . $sep . "Not quoted";
}
}
echo $br;
}

How do i save query result as .csv file? [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
What is the most efficient way to convert a MySQL query to CSV in PHP please?
It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required).
The CSV should also include one top line of field names.
SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;
(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)
or:
$select = "SELECT * FROM table_name";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
Check out this question / answer. It's more concise than #Geoff's, and also uses the builtin fputcsv function.
$result = $db_con->query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.
SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test_table;
An update to #jrgns (with some slight syntax differences) solution.
$result = mysql_query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)
These functions setup the headers:
function setExcelContentType() {
if(headers_sent())
return false;
header('Content-type: application/vnd.ms-excel');
return true;
}
function setDownloadAsHeader($filename) {
if(headers_sent())
return false;
header('Content-disposition: attachment; filename=' . $filename);
return true;
}
This one sends a CSV to a stream using a mysql result
function csvFromResult($stream, $result, $showColumnHeaders = true) {
if($showColumnHeaders) {
$columnHeaders = array();
$nfields = mysql_num_fields($result);
for($i = 0; $i < $nfields; $i++) {
$field = mysql_fetch_field($result, $i);
$columnHeaders[] = $field->name;
}
fputcsv($stream, $columnHeaders);
}
$nrows = 0;
while($row = mysql_fetch_row($result)) {
fputcsv($stream, $row);
$nrows++;
}
return $nrows;
}
This one uses the above function to write a CSV to a file, given by $filename
function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
$fp = fopen($filename, 'w');
$rc = csvFromResult($fp, $result, $showColumnHeaders);
fclose($fp);
return $rc;
}
And this is where the magic happens ;)
function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
setExcelContentType();
setDownloadAsHeader($asFilename);
return csvFileFromResult('php://output', $result, $showColumnHeaders);
}
For example:
$result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
csvToExcelDownloadFromResult($result);
// Export to CSV
if($_GET['action'] == 'export') {
$rsSearchResults = mysql_query($sql, $db) or die(mysql_error());
$out = '';
$fields = mysql_list_fields('database','table',$db);
$columns = mysql_num_fields($fields);
// Put the name of all fields
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
}
$out .="\n";
// Add all values in the table
while ($l = mysql_fetch_array($rsSearchResults)) {
for ($i = 0; $i < $columns; $i++) {
$out .='"'.$l["$i"].'",';
}
$out .="\n";
}
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=search_results.csv");
echo $out;
exit;
}

PHP Mysql table conversion to excel:The file you are trying to open is in a different format than specified by the extension

I have a code that converts mysql table to excel sheet. It converts and the excel sheet is downloaded but whenever I try to open the file it gives an error msg in excel 2007:"The file you are trying to open is in a different format than specified by the extension...".The excel sheet opens after I click on 'Yes' but it is nothing but a white blank sheet.I have seen the similar posts but none of them solves my problem...Please help...Thank you
<?php
include('dbcon.php');
?>
<?php
$sql = "SELECT * FROM stu_gen_info";
$rec = mysql_query($sql) or die (mysql_error());
$num_fields = mysql_num_fields($rec);
for($i = 0; $i < $num_fields; $i++ )
{
$header .= mysql_field_name($rec,$i)."\\t";
}
while($row = mysql_fetch_row($rec))
{
$line = '';
foreach($row as $value)
{
if((!isset($value)) || ($value == ""))
{
$value = "\\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\\n";
}
$data = str_replace("\\r" , "" , $data);
if ($data == "")
{
$data = "\\n No Record Found!\n";
}
header("Content-Type: application/vnd.ms-excel");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=reports.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\\n$data";
?>
try adding this
header("Content-Type: application/vnd.ms-excel");

PHP Array to CSV

I'm trying to convert an array of products into a CSV file, but it doesn't seem to be going to plan. The CSV file is one long line, here is my code:
for($i=0;$i<count($prods);$i++) {
$sql = "SELECT * FROM products WHERE id = '".$prods[$i]."'";
$result = $mysqli->query($sql);
$info = $result->fetch_array();
}
$header = '';
for($i=0;$i<count($info);$i++)
{
$row = $info[$i];
$line = '';
for($b=0;$b<count($row);$b++)
{
$value = $row[$b];
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
array_to_CSV($data);
function array_to_CSV($data)
{
$outstream = fopen("php://output", 'r+');
fputcsv($outstream, $data, ',', '"');
rewind($outstream);
$csv = fgets($outstream);
fclose($outstream);
return $csv;
}
Also, the header doesn't force a download. I've been copy and pasting the output and saving as .csv
EDIT
PROBLEM RESOLVED:
If anyone else was looking for the same thing, found a better way of doing it:
$num = 0;
$sql = "SELECT id, name, description FROM products";
if($result = $mysqli->query($sql)) {
while($p = $result->fetch_array()) {
$prod[$num]['id'] = $p['id'];
$prod[$num]['name'] = $p['name'];
$prod[$num]['description'] = $p['description'];
$num++;
}
}
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=pressurecsv.csv");
fputcsv($output, array('id','name','description'));
foreach($prod as $product) {
fputcsv($output, $product);
}
fclose($output) or die("Can't close php://output");
Instead of writing out values consider using fputcsv().
This may solve your problem immediately.
Note from comment: I should mention that this will be making a file on your server, so you'll need to read that file's contents before outputting it, also if you don't want to save a copy then you'll need to ùnlink`the file when you are done
This is a simple solution that exports an array to csv string:
function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
$f = fopen('php://memory', 'r+');
foreach ($data as $item) {
fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
}
rewind($f);
return stream_get_contents($f);
}
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));
Reference
Try using;
PHP_EOL
To terminate each new line in your CSV output.
I'm assuming that the text is delimiting, but isn't moving to the next row?
That's a PHP constant. It will determine the correct end of line you need.
Windows, for example, uses "\r\n". I wracked my brains with that one when my output wasn't breaking to a new line.
how to write unified new line in PHP?
I know this is old, I had a case where I needed the array key to be included in the CSV also, so I updated the script by Jesse Q to do that.
I used a string as output, as implode can't add new line (new line is something I added, and should really be there).
Please note, this only works with single value arrays (key, value). but could easily be updated to handle multi-dimensional (key, array()).
function arrayToCsv( array &$fields, $delimiter = ',', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = '';
foreach ( $fields as $key => $field ) {
if ($field === null && $nullToMysqlNull) {
$output = '';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output .= $key;
$output .= $delimiter;
$output .= $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
$output .= PHP_EOL;
}
else {
$output .= $key;
$output .= $delimiter;
$output .= $field;
$output .= PHP_EOL;
}
}
return $output ;
}
In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to blow apart the array completely:
function array2csv($array, &$title, &$data) {
foreach($array as $key => $value) {
if(is_array($value)) {
$title .= $key . ",";
$data .= "" . ",";
array2csv($value, $title, $data);
} else {
$title .= $key . ",";
$data .= '"' . $value . '",';
}
}
}
Since the various levels of my array didn't lend themselves well to a the flat CSV format, I created a blank column with the sub-array's key to serve as a descriptive "intro" to the next level of data. Sample output:
agentid fname lname empid totals sales leads dish dishnet top200_plus top120 latino base_packages
G-adriana ADRIANA EUGENIA PALOMO PAIZ 886 0 19 0 0 0 0 0
You could easily remove that "intro" (descriptive) column, but in my case I had repeating column headers, i.e. inbound_leads, in each sub-array, so that gave me a break/title preceding the next section. Remove:
$title .= $key . ",";
$data .= "" . ",";
after the is_array() to compact the code further and remove the extra column.
Since I wanted both a title row and data row, I pass two variables into the function and upon completion of the call to the function, terminate both with PHP_EOL:
$title .= PHP_EOL;
$data .= PHP_EOL;
Yes, I know I leave an extra comma, but for the sake of brevity, I didn't handle it here.
The easiest way to create csv file from an array is to use implode() function:
<?php
$arr = array('A','B','C','D');
echo implode(",",$arr);
?>
The output of the above code will give:
A,B,C,D
Arrays of data are converted into csv 'text/csv' format by built in php function fputcsv takes care of commas, quotes and etc..
Look at
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
http://www.php.net/manual/en/function.fputcsv.php
It worked for me.
$f=fopen('php://memory','w');
$header=array("asdf ","asdf","asd","Calasdflee","Start Time","End Time" );
fputcsv($f,$header);
fputcsv($f,$header);
fputcsv($f,$header);
fseek($f,0);
header('content-type:text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($f);```
I use this simple function to create every single array entry as csv:
function arrayToCsv($fields, $delimiter = ",", $enclosure = "\"", $escapeChar = "\"")
{
$fp = fopen('php://temp', 'r+');
fputcsv($fp, $fields, $delimiter, $enclosure, $escapeChar);
rewind($fp);
$ret = fgets($fp);
fclose($fp);
return $ret;
}
You can try below code to export csv from array using fputcsv
ob_start();
$outputCsv = fopen('php://output', 'w');
fputcsv($outputCsv, ['column 1', 'column 2' 'column 3'], ",");
fputcsv($outputCsv, ['','',''], ",");
fputcsv($outputCsv, ['value 1', 'value 2' 'value 3'], ",");
fputcsv($outputCsv, ['value 11', 'value 21' 'value 31'], ",");
fputcsv($outputCsv, ['value 12', 'value 22' 'value 31'], ",");
header('Cache-Control: max-age=0');
header("Expires: 0");
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-type: application/csv');
header('Content-Disposition: attachment;filename="doc_logs.csv"');
header("Content-Transfer-Encoding: binary");
fpassthru($outputCsv);
fclose($outputCsv);

PHP code to convert a MySQL query to CSV [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
What is the most efficient way to convert a MySQL query to CSV in PHP please?
It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required).
The CSV should also include one top line of field names.
SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;
(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)
or:
$select = "SELECT * FROM table_name";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
Check out this question / answer. It's more concise than #Geoff's, and also uses the builtin fputcsv function.
$result = $db_con->query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.
SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test_table;
An update to #jrgns (with some slight syntax differences) solution.
$result = mysql_query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)
These functions setup the headers:
function setExcelContentType() {
if(headers_sent())
return false;
header('Content-type: application/vnd.ms-excel');
return true;
}
function setDownloadAsHeader($filename) {
if(headers_sent())
return false;
header('Content-disposition: attachment; filename=' . $filename);
return true;
}
This one sends a CSV to a stream using a mysql result
function csvFromResult($stream, $result, $showColumnHeaders = true) {
if($showColumnHeaders) {
$columnHeaders = array();
$nfields = mysql_num_fields($result);
for($i = 0; $i < $nfields; $i++) {
$field = mysql_fetch_field($result, $i);
$columnHeaders[] = $field->name;
}
fputcsv($stream, $columnHeaders);
}
$nrows = 0;
while($row = mysql_fetch_row($result)) {
fputcsv($stream, $row);
$nrows++;
}
return $nrows;
}
This one uses the above function to write a CSV to a file, given by $filename
function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
$fp = fopen($filename, 'w');
$rc = csvFromResult($fp, $result, $showColumnHeaders);
fclose($fp);
return $rc;
}
And this is where the magic happens ;)
function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
setExcelContentType();
setDownloadAsHeader($asFilename);
return csvFileFromResult('php://output', $result, $showColumnHeaders);
}
For example:
$result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
csvToExcelDownloadFromResult($result);
// Export to CSV
if($_GET['action'] == 'export') {
$rsSearchResults = mysql_query($sql, $db) or die(mysql_error());
$out = '';
$fields = mysql_list_fields('database','table',$db);
$columns = mysql_num_fields($fields);
// Put the name of all fields
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
}
$out .="\n";
// Add all values in the table
while ($l = mysql_fetch_array($rsSearchResults)) {
for ($i = 0; $i < $columns; $i++) {
$out .='"'.$l["$i"].'",';
}
$out .="\n";
}
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=search_results.csv");
echo $out;
exit;
}

Categories