2

How can i convert my 2d array into csv file with adding header so user can upload the file directly.

Here is my array

Array (   
    [0] => Array
        (
            [0] => 25/2/2013
            [1] => 8.45 a.m
            [2] => 9.98
            [3] => 1.23
            [4] => 6.1
        )

    [1] => Array
        (
            [0] => 25/2/2013
            [1] => 8.46 a.m
            [2] => 9.02
            [3] => 1.75
            [4] => 1.75
        )
 )

and i want my output as

Date Time Value1 Value2 Value3 (all header)

25/2/2013 8.45 a.m 9.98 1.23 6.1

25/2/2013 8.46 a.m 9.02 1.75 1.75

3

1 Answer 1

11
   $header = array("Date","Time","Value1","Value2","Value3");

   $fp = fopen("php://output", "w");
   fputcsv ($fp, $header, "\t");
   foreach($array as $row){
        fputcsv($fp, $row, "\t");
   }
   fclose($fp);

If you want to trigger a download for the client add the following lines at the top.

  header("Content-Type: text/csv");
  header('Content-disposition: attachment;filename=mycoolfile.csv');
Sign up to request clarification or add additional context in comments.

4 Comments

do you mind explaining this a bit? Whats \t ? What in here handles that the array is multidimensional? How is the array written into the csv? With brackets? Comma? Will it work with more than 2D?
@sumit look up fputcsv and all will be reveiled
@sumit also \t is the escape sequence for the tab character. The output is not going to a file at this point but to php://output which is the file descriptor for the output buffer. any writable filename in the fopen call can be used instead.
if the PHP documentation would be any useful, nobody would search here for the answers ;) I'm using fputcsv already.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.