Search code examples
phpcsvforeachfputcsv

fputcsv only returning one row from array


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


Solution

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

    $export_data = stream_get_contents($outstream);