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

2
  • Why aren't you just using $order_data? Commented Aug 18, 2011 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.) Commented Aug 18, 2011 at 20:57

1 Answer 1

4

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

$export_data = stream_get_contents($outstream);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.