Benny150592 Posted October 14, 2013 Share Posted October 14, 2013 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 Link to comment https://forums.phpfreaks.com/topic/282953-writing-an-array-to-a-csv/ Share on other sites More sharing options...
Ch0cu3r Posted October 14, 2013 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. Link to comment https://forums.phpfreaks.com/topic/282953-writing-an-array-to-a-csv/#findComment-1453839 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 Link to comment https://forums.phpfreaks.com/topic/282953-writing-an-array-to-a-csv/#findComment-1453841 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.