使用 PHP 函数 fputcsv 写入 CSV

Write to CSV with PHP function fputcsv

我正在使用 fputcsv 从 MySQL 结果写入 CSV:

$list = array("group, variable, value \r\n");

while ($row = mysqli_fetch_assoc($result)) {
  array_push($list, $row['strand_pk'] . ',' . $row['unit_name']. "\r\n");
}

$fp = fopen('../reports/data.csv', 'w');

fputcsv($fp, $list);

fclose($fp);

打印在浏览器页面上的数组如下所示:

Array
(
    [0] => group, variable, value 

    [1] => 1,Integrated Medical Systems 1

    [2] => 1,Integrated Medical Systems 2

    [3] => 1,Integrated Medical Practice 1
    
    ...
)

具有输出的 CSV 如下所示:

"group, variable, value 
","1,Integrated Medical Systems 1
","1,Integrated Medical Systems 2
","1,Integrated Medical Practice 1
..."

我需要的是 CSV 格式:

group,variable,value
1,IMP 3,40
1,IMP 2,8
1,IMP 1,54
1,IMS 2,10

我做错了什么?

fputcsv 需要正确的 one-dimensional 数组(不是 comma-separated 字符串)。

您的代码应如下所示:

$list = ['group', 'variable', 'value'];

while ($row = mysqli_fetch_assoc($result)) {
   $list[] = [$row['strand_pk'], $row['unit_name']];  // you're missing a value here though
}

然后你需要在写入文件之前遍历数组:

foreach ($list as $row) {
  fputcsv($fp, $row);
}

请注意,如果您只需要用它创建 CSV,则可能根本不需要构建 $list。然后在 while 循环中直接使用 fputcsv