【问题标题】:Wordpress converting array to csv for downloadWordpress 将数组转换为 csv 以供下载
【发布时间】:2017-02-07 18:44:03
【问题描述】:

我有以下函数,它从数据库查询中获取一组结果。我在遍历查询结果时填充数组。同时我创建了一个html表。输出 html 表后,我调用函数 download_csv($csvArray) 但没有下载 CSV,它只显示数组的内容,就好像我在数组上做了 var_dump 一样。我可以确认数组的内容是正确的。

注意:这是在外部网页上完成的,而不是来自管理区域。

是否需要调用一些 wordpress 函数才能允许下载,还是我遗漏了什么?

function download_csv($csvArray) {
    $file_name = 'report.csv';
    //output headers so that the file is downloaded rather than displayed
    header("Content-Type: text/csv");
    header("Content-Disposition: attachment; filename=$file_name");
    //Disable caching - HTTP 1.1
    header("Cache-Control: no-cache, no-store, must-revalidate");
    //Disable caching - HTTP 1.0
    header("Pragma: no-cache");
    //Disable caching - Proxies
    header("Expires: 0");

    //Start the ouput
    $output = fopen("php://output", "w");

    //Then loop through the rows
    foreach ($csvArray as $fields) {
        fputcsv($output, $fields);
    }
    //Close the stream off
    fclose($output);
    die();
}

【问题讨论】:

标签: php wordpress csv export


【解决方案1】:

以下代码将帮助您将 Array 转换为 CSV 并使其自动下载 更改 die();退出函数();并使用内爆功能。它会起作用的。

header('Content-Type: text/csv; charset=UTF-8');
  header('Content-Disposition: attachment; filename=sample.csv');
  header('Pragma: no-cache');
  header('Expires: 0');
  $fp = fopen('php://output', 'w');
  //ex: $list={...};


  foreach ($list as $fields) 
  {
  fputcsv($fp,implode($fields, ','));
  }
  fclose($fp);
  exit();

【讨论】:

  • 即使使用 exit(),它仍然在输出数组的内容;
  • 需要在fputcsv() 中单独使用implode( ', ', $fields ) 而不是$fields。因为数组需要转换成CSV的可打印逗号分隔格式。
  • $array = array('value1',12323,'"04.07.2012 12:10:52"'); $array = str_replace('"', '', $array); fputcsv($fp, $array); 试试这个。并从上面的代码中获取参考。
猜你喜欢
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 2011-04-25
  • 2011-11-22
  • 2022-01-17
相关资源
最近更新 更多