donglvmang8638
2013-10-08 06:01
浏览 56
已采纳

在我的插件中创建一个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

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

2条回答 默认 最新

  • doutai1509 2013-10-08 06:23
    已采纳

    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.

    打赏 评论
  • 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 );
    
        $fields="id".","."Name"."
    ";
    

    Fetch content from foreach loop

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

       echo $fields.$data;
       exit;
    

    打赏 评论

相关推荐 更多相似问题