I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.
I have the e-mailing of the link, MySQL query, etc. covered.
<To have it send it as a CSV and have it give the file name, use header():
http://us2.php.net/header
header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');
As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.
Instead of:
$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00' AND created<='{$end} 23:59:59' ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
$result.="{$row['email']},";
$result.="\n";
echo $result;
}
Use:
$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00' AND created<='{$end} 23:59:59' ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
echo implode(",", $row)."\n";
}
How to write in CSV file using PHP script? Actually I was also searching for that too. It is kind of easy task with PHP. fputs(handler, content) - this function works efficiently for me. First you need to open the file in which you need to write content using fopen($CSVFileName, ‘wb’).
$CSVFileName = “test.csv”;
$fp = fopen($CSVFileName, ‘wb’);
//Multiple iterations to append the data using function fputs()
foreach ($csv_post as $temp)
{
$line = “”;
$line .= “Content 1″ . $comma . “$temp” . $comma . “Content 2″ . $comma . “16/10/2012″.$comma;
$line .= “\n”;
fputs($fp, $line);
}
Already very good solution came. I'm just puting the total code so that a newbie get total help
<?php
extract($_GET); //you can send some parameter by query variable. I have sent table name in *table* variable
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$table.csv");
header("Pragma: no-cache");
header("Expires: 0");
require_once("includes/functions.php"); //necessary mysql connection functions here
//first of all I'll get the column name to put title of csv file.
$query = "SHOW columns FROM $table";
$headers = mysql_query($query) or die(mysql_error());
$csv_head = array();
while ($row = mysql_fetch_array($headers, MYSQL_ASSOC))
{
$csv_head[] = $row['Field'];
}
echo implode(",", $csv_head)."\n";
//now I'll bring the data.
$query = "SELECT * FROM $table";
$select_c = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
foreach ($row as $key => $value) {
//there may be separator (here I have used comma) inside data. So need to put double quote around such data.
if(strpos($value, ',') !== false || strpos($value, '"') !== false || strpos($value, "\n") !== false) {
$row[$key] = '"' . str_replace('"', '""', $value) . '"';
}
}
echo implode(",", $row)."\n";
}
?>
I have saved this code in csv-download.php
Now see how I have used this data to download csv file
<a href="csv-download.php?table=tbl_vfm"><img title="Download as Excel" src="images/Excel-logo.gif" alt="Download as Excel" /><a/>
So when I have clicked the link it download the file without taking me to csv-download.php page on browser.
Try:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "record1,record2,record3\n";
die;
etc
Edit: Here's a snippet of code I use to optionally encode CSV fields:
function maybeEncodeCSVField($string) {
if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
$string = '"' . str_replace('"', '""', $string) . '"';
}
return $string;
}
Here is an improved version of the function from php.net that @Andrew posted.
function download_csv_results($results, $name = NULL)
{
if( ! $name)
{
$name = md5(uniqid() . microtime(TRUE) . mt_rand()). '.csv';
}
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='. $name);
header('Pragma: no-cache');
header("Expires: 0");
$outstream = fopen("php://output", "wb");
foreach($results as $result)
{
fputcsv($outstream, $result);
}
fclose($outstream);
}
It is really easy to use and works great with MySQL(i)/PDO result sets.
download_csv_results($results, 'your_name_here.csv');
Remember to exit()
after calling this if you are done with the page.