home   articles   tags   browse code   

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).

<?php

    $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)
        rtrim_csv_out($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:
"productid","userid","quantity","cost","description",
"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",
 

Tags: php, csv
 
Pradeep Saini on Aug 21st, 2009 6:23 am said:
Thankyou very much for this article. This is very helpful for me. I resolved my issue after get this one. Thanks again. Cheers
 

Awesome on Aug 29th, 2009 5:47 pm said:
Really an awesome tutorial, helped us alot!! Thanks..
 



 

 



Related Articles
 



home  |  privacy policy  |  terms of use  |  contact  


©2013, Zedwood.com

zedwood.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon.com