Write to CSV with PHP function fputcsv

292 Views Asked by At

I am using fputcsv to write to a CSV from MySQL results:

$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);

The array when printed on the browser page looks like:

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

    [1] => 1,Integrated Medical Systems 1

    [2] => 1,Integrated Medical Systems 2

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

The CSV with output looks like:

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

What I need is the CSV to look like:

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

What am I doing wrong here?

1

There are 1 best solutions below

0
On BEST ANSWER

fputcsv expects proper, one-dimensional arrays (not comma-separated strings).

Your code should look something like this:

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

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

Then you'll need to loop over the array before writing into the file:

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

Note that you might not need to build $list at all if you only need to create the CSV with it. Use fputcsv directly within your while loop then.