Benny150592 Posted October 14, 2013 Share Posted October 14, 2013 (edited) Hi Guys, I'm trying to write an array to a CSV file and having no luck using fputcsv. The array I'm getting back contains the information and it should be being written to the database every time the for loop goes round, but all I'm getting is an empty CSV. Any ideas? $fileName = date('d m Y') . '.csv'; $fp = fopen($fileName, 'w'); header('Content-Description: File Transfer'); header('Content-Type: text/csv'); header("Content-Disposition: attachment; filename=\"$fileName\""); $csvData = array(); for($j =0; $j < $messageAmount; $j++){ $messageNumber = $message->messages[$j]->number; $messageBody = $message->messages[$j]->message; $messageDate = $message->messages[$j]->date; $csvData[$j] = array($messageNumber,$messageBody,$messageDate); fputcsv ($fp, $csvData[$j]); } fclose($fp); ?> This is the code I'm using btw. Regards, Ben Edited October 14, 2013 by Benny150592 Quote Link to comment Share on other sites More sharing options...
Solution Ch0cu3r Posted October 14, 2013 Solution Share Posted October 14, 2013 You're creating the file, sending headers so the file downloads and then writing the contents to the file. You need to write the data to the file first, before you send the headers. Quote Link to comment Share on other sites More sharing options...
Barand Posted October 14, 2013 Share Posted October 14, 2013 or instead of of writing to file you can write to STDOUT $fp = fopen('php://output', 'w'); // so you can fputcsv to STDOUT Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.