-2

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?

IlludiumPu36
  • 4,196
  • 10
  • 61
  • 100
  • `fputcsv` writes _one line_ to the CSV, you are trying to use it to write the whole array of multiple lines at once. And your “line” data is not actually an array as it should be, but a string of comma -separated values. – 04FS Oct 06 '20 at 07:08

1 Answers1

2

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.

Jeto
  • 14,596
  • 2
  • 32
  • 46