Export WordPress Table to CSV from page

I want to export my members table to csv format on my default download location. So I used a shortcode in functions.php and called it on a page. I am getting an already sent header warning and csv file is not exported but data is printed on the screen with header already sent error warning. Can anybody help me export the file and also remove the error of header sent. Thanks

Error Message

Warning: Cannot modify header information - headers already sent by (output started at D:\xamp\htdocs\wordpress\wp-includes\class.wp-styles.php:119) in D:\xamp\htdocs\wordpress\wp-content\themes\jupiter\functions.php on line 1005

Shortcode code in functions.php file

add_shortcode('exporttocsv','exporttocsv');
function exporttocsv()
{

$host="localhost";
$user="root";
$pass="";
$db = 'w';
$table="groups";
$file="export";

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";

$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
$string=ob_get_contents();
    ob_end_clean(); 
    return $string;
exit;
}

This is how I call it on a page

[exporttocsv]

0

Leave a Comment