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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号