【问题标题】:creating a CSV file from MySQL Table data in PHP在 PHP 中从 MySQL 表数据创建 CSV 文件
【发布时间】:2015-03-09 00:24:15
【问题描述】:

我在 PHP 中有这段代码:

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=calls.csv');

// create a file pointer connected to the output stream
$output = fopen($_SERVER["DOCUMENT_ROOT"].'/file_dump/price_tariffs/calls.csv', 'w');

// output the column headings
fputcsv($output, array('Column 1', 'Column 2'));

// loop over the rows, outputting them
$sql="SELECT * from call_costs where sequence < '50' ";
$rs=mysql_query($sql,$conn);
while($result = mysql_fetch_array($rs)) {
    fputcsv($output, $result["number"]);
}

它在 price_tariffs 目录中创建文件名 calls.csv,但它只添加第 1 列和第 2 列,而不是来自 while 循环的数据

我已经检查了循环并在循环内回显数据,显示正常

【问题讨论】:

  • print_r 之一的 $result["number"] 输出是什么?
  • 另外,您是要将其保存到文件中,还是让浏览器下载内容?

标签: php mysql csv


【解决方案1】:

fputcsv 将第二个参数作为数组(),“并且您已经在循环之外使用了 fputcsv,将第二个参数作为数组传递”[*] 里面有两个值。 尝试在循环中做同样的事情:

fputcsv($output, array($result["number"], $result["somethingelse"]));

[*]:已编辑,在下面的 cmets 中澄清后添加了引用的句子。

【讨论】:

  • 我认为这是因为关于fputcsv 的信息不正确,您曾说过它采用带有两个值的第二个参数。实际上,第二个参数只包含一个任意长度值的数组,而不仅限于两个值。
  • 哦,我肯定错了,因为我的英语很差:当然我不是说第二个参数数组只包含两个值。我不知何故(在我看来)指的是他已经在第一个 fputccsv [fputcsv($output, array('Column 1', 'Column 2'));] 上存储了两个值,所以我认为他想要再次输出两列......无论如何,这是我的错,赢得了反对票:P
  • 我刚刚修正了我的答案,并添加了一个关于这些 cmets 的注释。
【解决方案2】:

manual 中查看mysql_fetch_array,所以,我们可以说:

...
while($result = mysql_fetch_array($rs,MYSQL_NUM)) {
    fputcsv($output, $result);
}

只需添加第二个可选参数MYSQL_NUM 即可返回数值数组并将其全部作为fputcsv 中的参数提供。通过这种方式,您将在 文件中获取所有原始字段数据。

【讨论】:

    【解决方案3】:

    由于您将数据直接发送到客户端,因此您应该回显它而不是将其保存到文件中:) 改为打开 php://output

    试试这个(来自powtacs answer

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=calls.csv');
    
    // create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');
    
    // output the column headings
    fputcsv($output, array('Column 1', 'Column 2'));
    
    // loop over the rows, outputting them
    $sql="SELECT * from call_costs where sequence < '50' ";
    $rs=mysql_query($sql,$conn);
    while($result = mysql_fetch_assoc($rs)) {
        fputcsv($output, $result);
    }
    

    另外请注意 mysql 已被贬值,您应该改用 mysqli 或 PDO

    【讨论】:

      【解决方案4】:

      只选择你想要的列:

      $sql = "SELECT column1, column2 FROM call_costs WHERE sequence < '50'";
      

      然后使用mysql_fetch_assoc() 获取每一行作为关联数组,并输出:

      $rs=mysql_query($sql,$conn);
      while($row = mysql_fetch_assoc($rs)) {
          fputcsv($output, $row);
      }
      

      fputcsv() 的第二个参数应该是应该放入 CSV 文件字段中的值的数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-19
        • 1970-01-01
        • 1970-01-01
        • 2017-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多