2013-10-08 06:01
浏览 56


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

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);
// Execute the function

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutai1509 2013-10-08 06:23

    As per the PHP documentation stated at:

    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.

    打赏 评论
  • dongsuo0517 2013-10-08 06:14

    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 );

    Fetch content from foreach loop

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

       echo $fields.$data;

    打赏 评论

相关推荐 更多相似问题