posted by kevin on May 24, 2009

CSV stands for 'comma-seperated-values.' These files are very commonly used to export and import data into different databases or Microsoft Excel.

Even though it it a relatively simple thing to do, I thought I would add it to my toolkit since it is something that I do quite frequently.

The nature of the format makes it so the file is very structured. The top row contains the field names, the rest of the rows are the records.

My thought was to just pass an array to a method and the browser will prompt the user to download the .csv file. Simple enough.

 
//file named CA_CSV.php
class CA_CSV {
 
    public static function download($arrays, $filename = 'output.csv') {
        $string = '';
        $c=0;
        foreach($arrays AS $array) {
            $val_array = array();
            $key_array = array();
            foreach($array AS $key => $val) {
                $key_array[] = $key;
                $val = str_replace('"', '""', $val);
                $val_array[] = "\"$val\"";
            }
            if($c == 0) {
                $string .= implode(",", $key_array)."\n";
            }
            $string .= implode(",", $val_array)."\n";
            $c++;
        }
        CA_FileDownload::download($string, $filename);
    }
 
}
 

Now this method simply takes in the string of data and the name that you want to give the file that you will prompt the user to download.

 
 
<?php
//File Named CA_FileDownload.php
/**
 * File Download
 * 
 * Many times you need to prompt somebody to download
 * the string of data you have as a file and name the file
 * for them.
 * 
 * This isn't exactly rocket science... but it's handy.
 *
 * @author Kevin Korb
 */
Class CA_FileDownload {
 
    /**
     * Download
     * 
     * Simply pass in the string of data you want to be
     * in the file and then the filename and it will
     * prompt the user to download it. (Just make sure
     * this is called before anything is transferred to the
     * browser.
     *
     * @param string $string
     * @param string $filename
     */
    public static function download($string, $filename) {
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: private");
        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=$filename");
        header("Accept-Ranges: bytes");
        echo $string;
        exit;
    }
 
}
?>
 

Now here is the demo code to test out our CSV Generator

 
$array_for_csv = array(
    array(
        'id' => 3,
        'name' => 'Kevin',
        'position' => 'PHP Developer',
        'city' => "St. Louis",
        'state' => 'MO'
    ),
    array(
        'id' => 5,
        'name' => 'Billy',
        'position' => 'Cook',
        'city' => "St. Charles",
        'state' => 'MO'
    ),
    array(
        'id' => 349,
        'name' => 'Freddy',
        'position' => 'Painter',
        'city' => "O'Fallon",
        'state' => 'MO'
    ),
);
 
CA_CSV::download($array_for_csv);
?>
 

Click Here To See The Results.

6 comments to "CSV PHP Creation - Simple Class"

#126
Pigiman says:
May 8, 2010 at 11:13 am
hey, does it work with Hebrew characters\utf8? thanks
#127
Harshit says:
May 8, 2010 at 01:48 pm
Just gonna modify this and try it out. If this works, you just saved someone an extra hour! :0)
#129
Shahar says:
May 12, 2010 at 04:18 am
Great, just what I was looking for, thanks!
#131
John M says:
May 17, 2010 at 06:22 pm
Do you actually have to spell out the data being input in the $array_for_csv? If so, this seems like overkill if the goal is to have it simply pull the data from a database or variables collected during a form.
#132
May 17, 2010 at 06:31 pm
@john, of course not, that array was an example of how it should be formatted and a usage example in it's simplest form. I don't care how the data gets into the array, I am just showing the array to csv. I could have shown db to array to csv, or form to array to csv, but decided to break it down to the simplest form, assuming the reader will connect the other dots.
#140
Rambabu says:
June 8, 2010 at 12:01 am
Thanks. How to display the chinese language
Bookmark and Share

Leave a Comment

Your email address will not be published.

(You can enclose code in <php></php> blocks.)

You may use Markdown syntax.

Please enter the letters as they are shown in the image above.
Letters are not case-sensitive.