Create CSV file from MySql table( not data table from webpage) - DEPRECATED
<?php
/*
ref:
http://stackoverflow.com/questions/125113/php-code-to-convert-a-mysql-query-to-csv
DB_NAME: listing_members
DB_TABLE: members
*/
$link = mysql_connect('localhost', 'root', 'popadmin');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make listing_members the current db
$db_selected = mysql_select_db('listing_members', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$result = mysql_query('SELECT * FROM `members`');
if (!$result) die('Couldn\'t fetch records');
// how many fields on the table:
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
// returns the name of the specified field index
$headers[] = mysql_field_name($result , $i);
}
// $fp: file pointer
$fp = fopen('php://output', 'w'); // write permissions
if ($fp && $result)
{
header('Content-Type: text/csv');
// change the export filename here
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
//format line as CSV and write to file pointer $fp
fputcsv($fp, array_values($row));
}
die;
}