Search This Blog

Saturday, April 30, 2011

Best way to create a CSV file in PHP

I have seen many php scripts trying to create CSV's using strings and adding commas inside a for loop. But this method is prone to errors since it doesn't work properly with special characters like comma and quotation. This function use php fputcsv to create a CSV file in the server memory rather than the disk making its faster to retrieve the CSV file.

$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;
    }


No comments: