Generate CSV Spreadsheet with PHP

A CSV is a comma separated value text file, which is pretty much a spreadsheet text file. There are other popular formats like tab delimited files as well. It is difficult to generate an xls spreadsheet on the fly, and so many use php generated CSV to export data from mysql databases.

It is simple to generate a CSV file, but the real key are those two header() functions below, which tell the browser to open the file in the default spreadsheet editor (usually excel on windows).
    $filename = date("Ymd")."_csvfile.csv";
    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=$filename");
    $field_arr = array('productid','userid','quantity','cost','description');
    foreach($field_arr as $val)
    echo "\n";
    for($i=0; $i<10; $i++)
        rtrim_csv_out( rand( 0,1000) );
        rtrim_csv_out( rand( 0, 100) );
        rtrim_csv_out( rand(50, 150) );
        rtrim_csv_out( sprintf("%1.2f", rand(0,23)/100 ) );
        rtrim_csv_out( "description test $i" );
        echo "\n";
    function rtrim_csv_out($str)
        echo '"'.rtrim(str_replace('"','""',$str)).'",';

generates a csv file like:
"423","100","129","0.09","description test 0",
"27","13","114","0.07","description test 1",
"700","72","116","0.14","description test 2",
"33","48","70","0.18","description test 3",
"124","62","61","0.16","description test 4",
"564","88","123","0.22","description test 5",
"447","45","140","0.10","description test 6",
"367","7","147","0.14","description test 7",
"418","97","128","0.12","description test 8",
"194","84","117","0.12","description test 9",
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)

Pradeep Saini on 2009-08-21 12:23:38
Thankyou very much for this article. This is very helpful for me. I resolved my issue after get this one.
Thanks again.

Awesome on 2009-08-29 23:47:46
Really an awesome tutorial, helped us alot!! Thanks..