I want to print to excel as csv. This is where I am so far working from the answers.
<?php
$dbh = dbh_get();
header('Content-type: application/csv');
header("Content-Disposition: inline; filename=file.csv");
readfile('file.csv');
$sql = 'select t.*
from old t
where t.entered >= ? and t.entered < ?
and t.status <> \'cancel\'
and t.ccy = \'USD\'
order by id desc';
$stmt = $dbh->prepare($sql);
$v = array();
$v[] = $date->format(DateTime::ISO8601);
$v[] = $dateEnd->format(DateTime::ISO8601);
$numRows = 0;
$stmt->execute($v);
while (true) {
$r = $stmt->fetch();
if (is_bool($r)) break;
$numRows++;
$bop = $r['comments'];
$bop1 = strtok($bop, " "); //remove all but first word
$bop2 = substr(strstr($bop," "), 1); //remove first word and space
$headers = ['PLACE','YEAR','MONTH','COY','NT','TOPS','BOP','COUNTRY','REC','SENT','DESC'];
$fields = ["Old",2015,$textDate,$r['cols'],$r['nt'],$bop1,"NTR",$r['name'],$r['first_name'],$r['last_name'],$bop2];
$fp = fopen('file.csv', 'w');
fputcsv($fp, $headers);
fputcsv($fp, $fields);
fclose($fp);
}
dbh_free($dbh);
Still not working with this I get one line of code printed to screen, no download. What I need is to download the csv file so I can open it with excel.
Don't punish yourself by manually building a CSV. Use PHP's built in functionality instead.
<?php
$bop1 = 'bop1';
$bop2 = 'bop2';
$textDate = '2017-04-13';
$r = [
'ccy' => 'ccy',
'amount' => 'amount',
'name' => 'name',
'first_name' => 'first_name',
'last_name' => 'last_name',
];
$headers = ['column1','column2','column3','column4','column5','column6','column7','column8','column9','column10','column11'];
$fields = ["Old","2015",$textDate,$r['ccy'],$r['amount'],$bop1,"NTR",$r['name'],$r['first_name'],$r['last_name'],$bop2];
$fp = fopen('file.csv', 'w');
fputcsv($fp, $headers);
fputcsv($fp, $fields);
fclose($fp);
header('Content-type: application/csv');
header("Content-Disposition: inline; filename=file.csv");
readfile('file.csv');
Here's an updated example using your updated code:
<?php
$dbh = dbh_get();
$sql = 'select t.*
from old t
where t.entered >= ? and t.entered < ?
and t.status <> \'cancel\'
and t.ccy = \'USD\'
order by id desc';
$stmt = $dbh->prepare($sql);
$v = array();
$v[] = $date->format(DateTime::ISO8601);
$v[] = $dateEnd->format(DateTime::ISO8601);
$stmt->execute($v);
$fp = fopen('file.csv', 'w');
$headers = ['PLACE','YEAR','MONTH','COY','NT','TOPS','BOP','COUNTRY','REC','SENT','DESC'];
fputcsv($fp, $headers);
while ($r = $stmt->fetch()) {
$bop = $r['comments'];
$bop1 = strtok($bop, " "); //remove all but first word
$bop2 = substr(strstr($bop," "), 1); //remove first word and space
$fields = ["Old",2015,$textDate,$r['cols'],$r['nt'],$bop1,"NTR",$r['name'],$r['first_name'],$r['last_name'],$bop2];
fputcsv($fp, $fields);
}
fclose($fp);
dbh_free($dbh);
header('Content-type: application/csv');
header("Content-Disposition: inline; filename=file.csv");
readfile('file.csv');
You can do something like this:
$data = ['Old', '2015', $textDate];
file_put_contents('pathTofile.csv', implode(';', $data) . PHP_EOL, FILE_APPEND);
Update:
Now is some code more here, compared to the posted one liner. Just change the Content-Disposition header to this:
header('Content-Disposition: attachment; filename="'.basename('file.csv').'"');
it forces a download. See Content-Disposition and Read File
Related
I have a code which creates a .csv export of my table. Here is my code:
public function export(Request $request){
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="export.csv"');
$tb_name_alias = $request->tb_name;
$convert_alias_to_table_name = array('person' => "App\\persons");
$tb_name = $convert_alias_to_table_name[$tb_name_alias];
$arr = $tb_name::all()->toArray();
$newarr = array();
$size_of_outer_array = sizeof($arr);
For ( $i = 0; $i < $size_of_outer_array; $i++ ) {
$newarr[] = implode(",",$arr[$i]);
}
$fp = fopen('php://output', 'w');
foreach ( $newarr as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
}
It works as well, But when I import it again, it looks like this:
As you see, the column names aren't real .. they are col1, col2, etc ..! But I need to set some names as those column names. Like id, name, etc ..!
How can I do that?
try this
$fp = fopen('php://output', 'w');
fputcsv($fp, array('Column 1', 'Column 2', 'Column 3'));
foreach ( $newarr as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
While exporting file to CSV, space in the field "Sr. No", is removed after dot of "Sr.". I don't want that space to be removed. The code is as follow:
$filename = "file.csv";
$fp = fopen('php://output', 'w');
$array = array('Sr. No.','Name','DOB','Address');
$header = str_replace(' ', '', $array);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
$query = "select * from registratin";
$result = mssql_query($query);
$i = 1;
while($row = mssql_fetch_row($result)) {
$row = array_merge(array($i), $row);
fputcsv($fp, $row);
$i++;
}
Replace this:
$array = array('Sr. No.','Name','DOB','Address');
$header = str_replace(' ', '', $array);
With this:
$header = ['Sr. No.','Name','DOB','Address'];
I am a bit baffled as to why that str_replace call is there.
I want to create a csv file from some results in my database. But it display the content instead of prompting the download.
I know there are alot of questions about this, but no luck for me.
if(isset($_POST['export'])){
$resultExport = mysql_query("SELECT question.id, question.question, answer, A, B, C, D, question.publish
FROM question
INNER JOIN packagequestion
ON question.id = packagequestion.questionid
WHERE packagequestion.packageid = '".$packageID."' AND question.publish = 1
ORDER BY question.id DESC");
if (!$resultExport) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($resultExport);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($resultExport , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $resultExport)
{
// name the file by current category and package
$filename = $categorie."".$packageName;
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename.".csv");
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($resultExport))
{
fputcsv($fp, array_values($row));
}
die;
}
}
hope this will help you
<?php
include 'connection.php';
// Fetch Record from Database
$output = "";
$sql = mysql_query("select* from tablename");//your query
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
?>
for that you just have to remove following line from your code.
header('Content-Type: text/csv');
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;
}
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;
}