在我的插件中创建一个WordPress页面,将MySQL数据导出为CSV

I am looking to create a page in my wordpress plugin in which Export MySQL data from table as CSV and download it on click.I have following code

<?php
function fz_csv_export() {
$date = new DateTime();
$ts = $date->format( 'Y-m-d H:i:s' );
$result = array();
$result[] = array(
"first_name" => "Faison", "last_name" => "Zutavern",
"product_viewed" => "Sunglasses", "time_viewed" => $ts
);
$result[] = array(
"first_name" => "Faison", "last_name" => "Zutavern",
"product_viewed" => "Razor", "time_viewed" => $ts
);
$filename = "report-$ts.csv";
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
$hrow = $result[0];
fputcsv($fp, array_keys($hrow));
foreach ($result as $data) {
fputcsv($fp, $data);
}
fclose($fp);
}
// Execute the function
fz_csv_export();
?>

but it prints the data rather than download csv.Any help is appreciate

As per the PHP documentation stated at: http://php.net/manual/en/function.header.php

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

Just pass your headers at the beginning of the script, this will ensure that the headers are passed properly and the file can be downloaded.

Use This at place of csv file generating code

$filename = "report-$ts.csv";

    header( 'Content-Description: File Transfer' );
    header( 'Content-Disposition: attachment; filename=' . $filename );
    header( 'Content-Type: text/csv; charset=' . get_option( 'blog_charset' ), true );

    $fields="id".","."Name"."
";

Fetch content from foreach loop

foreach { $data .= $id.",".$name." "; }

   echo $fields.$data;
   exit;