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.
<You can simply write your data into CSV using fputcsv function. let us have a look at the example below. Write the list array to CSV file
$list[] = array("Cars", "Planes", "Ships");
$list[] = array("Car's2", "Planes2", "Ships2");
//define headers for CSV
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file_name.csv');
//write data into CSV
$fp = fopen('php://output', 'wb');
//convert data to UTF-8
fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));
foreach ($list as $line) {
fputcsv($fp, $line);
}
fclose($fp);
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
function outputCSV($data) {
$output = fopen("php://output", "wb");
foreach ($data as $row)
fputcsv($output, $row); // here you can change delimiter/enclosure
fclose($output);
}
outputCSV(array(
array("name 1", "age 1", "city 1"),
array("name 2", "age 2", "city 2"),
array("name 3", "age 3", "city 3")
));
php://output
fputcsv
<?
// Connect to database
$result = mysql_query("select id
from tablename
where shid=3");
list($DBshid) = mysql_fetch_row($result);
/***********************************
Write date to CSV file
***********************************/
$_file = 'show.csv';
$_fp = @fopen( $_file, 'wb' );
$result = mysql_query("select name,compname,job_title,email_add,phone,url from UserTables where id=3");
while (list( $Username, $Useremail_add, $Userphone, $Userurl) = mysql_fetch_row($result))
{
$_csv_data = $Username.','.$Useremail_add.','.$Userphone.','.$Userurl . "\n";
@fwrite( $_fp, $_csv_data);
}
@fclose( $_fp );
?>
The easiest way is to use a dedicated CSV class like this:
$csv = new csv();
$csv->load_data(array(
array('name'=>'John', 'age'=>35),
array('name'=>'Adrian', 'age'=>23),
array('name'=>'William', 'age'=>57)
));
$csv->send_file('age.csv');
Writing your own CSV code is probably a waste of your time, just use a package such as league/csv - it deals with all the difficult stuff for you, the documentation is good and it's very stable / reliable:
http://csv.thephpleague.com/
You'll need to be using composer. If you don't know what composer is I highly recommend you have a look: https://getcomposer.org/
Put in the $output
variable the CSV data and echo with the correct headers
header("Content-type: application/download\r\n");
header("Content-disposition: filename=filename.csv\r\n\r\n");
header("Content-Transfer-Encoding: ASCII\r\n");
header("Content-length: ".strlen($output)."\r\n");
echo $output;