Question

I'm having a hard time trying to figure out how to properly format these fputcsv lines.

Here is the code I am using to write my query to a csv file.

$handle = fopen( $dir .'/export.csv', 'w');
  $headers = 'Category Name, ID';
  fwrite($handle,$headers);

foreach( $catresults as $catresult ) {
  $csvcatname[0] = $catresult->name;
  $csvcatimage[1] = $catresult->term_id;
  fputcsv($handle, $csvcatname);
  fputcsv($handle, $csvcatimage); 
}

fclose($handle);
}

And this is how it is writing to the csv file. Category Names should be in Category Name column, and ID should be in the ID. If you look you can see that the first Category Name gets inserted into the second column header row along with the header name...

Category Name  |  IDShoes
66  
Pants   
65  
Lotions 
64  
findme  
69  
find me 
70  
with space  
71  
Find Second 
72  

Update

Thanks Barmar its now inserting to two columns. But the first data row is still inserting into my header row. Can I skip 1 row? This is how its showing up...

Category Name | IDShoes | 66
Was it helpful?

Solution

Each call to fputcsv writes another line to the file. If you want the line to have two columns, it must be an array with two elements. You're creating two arrays, each with one element, and writing them separately.

foreach( $catresults as $catresult ) {
    $row = array($catresult->name, $catresult->term_id);
    fputcsv($handle, $row);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top