$headerArray = array('Mon','Tue','Wed') ;
$bodyArray = array(array(1,2,3),
array(4,5,6));
function makeCsv($headerArray,$bodyArray) { $headerIncluded = false; $fp = fopen('php://temp/maxmemory:' . (5 * 1024 * 1024), 'r+'); // 5MB of memory allocated $content = $bodyArray; foreach ($content as $row) { if(!$headerIncluded) { $headerIncluded = true; fputcsv($fp, $headerArray); // create the csv file in the memory } fputcsv($fp, $row); } rewind($fp); $output = stream_get_contents($fp); // get csv file from the memory fclose($fp); return $output; }