3

This must be really simple... Following examples on here and php.net, I'm trying to get records from a mysql query, convert them to csv format, and assign this data to a variable for use in a program I have created. I would like to accomplish this without creating temporary files.

  public function export3() {
      $order_data = array();
      $order_data[] = array(
        'order_id',
        'email',
        'telephone',
        'shipping_address',
        'payment_address',
        'comment'
    );


    // Mysql returns data and is assigned to this array in the following format

    $order_data[] = array(
        '1',
        'blank@blank',
        '123456789',
        '123 Lane',
        '123 Lane',
        'no comment'
    );



    $order_data[] = array(
        '2',
        'blank3@blank3',
        '987654321',
        '321 Lane',
        '321 Lane',
        'no comment'
    );

    $outstream = fopen("php://temp", 'r+');

    foreach($order_data as $csv_data) {
        fputcsv($outstream, $csv_data);
    }

    rewind($outstream);
    $export_data = fgets($outstream);
    fclose($outstream);

    $response->output($export_data);

}

Unfortunately, I occasionally get complaints of "array to string" conversion, but even without any errors, I only get the first array (in csv format) but not the others. Any suggestions? Thank you

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Ben Glaser
  • 33
  • 4
  • Why aren't you just using `$order_data`? – cwallenpoole Aug 18 '11 at 17:44
  • How so? I'm open to any ideas... There's actually data from multiple queries that needs to be combined and then exported to a downloadable csv. (I left out those headers from the example above.) – Ben Glaser Aug 18 '11 at 20:57

1 Answers1

4

Use stream_get_contents() in place of fgets(), since the latter only fetches a single line.

$export_data = stream_get_contents($outstream);
salathe
  • 51,324
  • 12
  • 104
  • 132