Pro Tip : PHP has built in functions for reading and writing csv files

Just discovered this and I am mighty impressed. It seems that in PHP 5.1 and higher there are the functions fgetcsv() and fputcsv(). They make it pretty simple to read and write a csv file.

Here is a simple example which reads a csv file, adds a couple of fields and writes it to a new file.

<?php
 
// Open the output csv file
$outputfp = fopen('output.csv', 'w');
 
// Read from the input csv file
if (($inputfp = fopen("input.csv", "r")) !== FALSE) {
 
    while (($data = fgetcsv($inputfp, 1000, ",")) !== FALSE) {
 
        // Declare an array which will be used to hoe the new csv line
        $line=array();
 
        // Add the data from the read csv file to the output array
        $line[]=$data[0];
        $line[]=$data[1];
 
        // Add some more data, just because we can
        $line[]="another param";
        $line[]="yet another extra param";
 
        // Write the line to the file
        fputcsv($outputfp, $line);
    }
 
    // Clean up
    fclose($inputfp);
    fclose($outputfp);
}
 
?>

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">