1

What I want to do is, to export some dataset for Excel without using extra, 3rd party, heavy libraries.

The problem is, when I export the file, first row looks well, but starting from second row, it puts all $row data into first field of current row.

So I get file with first row properly placed in right columns and starting from second row instead of columns I see whole text in first field seperated by delimiter (comma)

enter image description here

Here is code snippet that I use for result.

        $counter=0;
        $file = fopen("sample.csv", "w");
        foreach ($registrants as $registrant) {
            $row = [
                'Fullname' => $registrant->fullname,
                'Phone' => $registrant->phone,
                'Email' => $registrant->email,
            ];
            if ($counter == 0)
                fputcsv($file, array_keys($row));
            fputcsv($file, $row);
            $counter++;
        }
        fclose($file);

Also tried to

         fputcsv($file, array_values($row), ';', ' ');

No success. What am I doing wrong? What is proper way to see correct result on all Excel versions regardless of OS or Excel locale and etc.?

heron
  • 3,611
  • 25
  • 80
  • 148
  • Check your export file. Is there a difference between the first and next rows? F.I. first row texts are enclosed by quotation marks and other rows not. Maybe you can add the first two rows from the export file as an output example for your question as well. I know Excel has a mind of its own if when comes to csv files. – Barry Jun 06 '15 at 12:22
  • The code looks OK, so open the file with simple text editor (Notepad) and see how the content looks. Is Excel set to use newlines for row separators? – VolenD Jun 06 '15 at 12:24
  • By the way, there is no proper way to cope with locales. Excel always uses the separator as defined by the user for csv files. – Barry Jun 06 '15 at 12:29
  • Looks like you want: `fputcsv($file, array_values($row));` instead of `fputcsv($file, $row);` – hek2mgl Jun 06 '15 at 13:05

0 Answers0