Jump to content

[SOLVED] Array to csv file


slamMan

Recommended Posts

@salathe

I will try that. I added an additional foreach statement and now I get the data in the output file, but it is all in one column and not in rows per record and the headers are not there. I expected the header to be missing since I haven't done anything to extract them yet, but I'm not sure why everything is in cell A1-AXX.

 

Here is the new code

$fp = fopen('imported' . date(mdyHis) . '.csv', 'w');


foreach ($list as $array) {
    foreach ($array as $line) {

fputcsv($fp, split(',', $line));
}
}


fclose($fp);

Assuming your array (as shown in the first post) is in $list then the code can be simpler than I think you think it should be.

 

$fp = fopen('imported' . date('mdyHis') . '.csv', 'w');
foreach ($list as $row) {
    fputcsv($fp, $row);
}
fclose($fp);

 

P.S. that gives the output (to the file):

123,abc,555-555-5555,,,,[email protected]
456,def,,,,,[email protected]

 

P.P.S. You could add the headers by doing the following immediately before the foreach loop:

fputcsv($fp, array_keys($list[0]));

I could have sworn I tried this and it didn't work, but using it the way you have it hear output the two rows of data.

 

Thank you very much!!!!

 

Now if I could just get the field names to show as the column headers it would be perfect.

 

Thanks for the help.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.