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

Link to comment
Share on other sites

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,,,,abc@123.com
456,def,,,,,def@123.com

 

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

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

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.