PHP: Read Write CSV

In this article, I will be showing you how to read and write CSV file with PHP.

I have used PHP function fgetcsv to read CSV fields and fputcsv to write on CSV file.

fgetcsv — Gets line from file pointer and parse for CSV fields.
fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.
This works on PHP 4 and PHP 5.

fputcsv — Format line as CSV and write to file pointer.
fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle.
This works on PHP 5 or greater.

DOWNLOAD SOURCE CODE

Read CSV file

The following code reads data from a CSV file read.csv and displays in tabular form.


<?php
if (($handle = fopen("read.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);		
        for ($c=0; $c < $num; $c++) {            
            echo $data[$c]; 
            echo "<br />";		
        }
    }
    fclose($handle);
}
?>

Write CSV file

The following code writes data to a CSV file file.csv. The data will be in the form of array. Each element will be the row of CSV file. The element of array is in comma separated form.


<?php
$list = array (
    'aaa,bbb,ccc,dddd',
    '123,456,789',
    '"aaa","bbb"'
);

$fp = fopen('file.csv', 'w');

foreach ($list as $line) {	
    fputcsv($fp, explode(',', $line));
}

fclose($fp);

echo "CSV File Written Successfully!";
?>

Read from one CSV file and write into the other

The following code read data from a CSV file read.csv and writes the same data to another CSV file readwirte.csv


<?php
// open the csv file in write mode
$fp = fopen('readwrite.csv', 'w');

// read csv file
if (($handle = fopen("read.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {                      
        // write csv file
		fputcsv($fp, $data);       	
	}
    fclose($handle);
	fclose($fp);
	
	echo "CSV File Written Successfully!";
}
?>

DOWNLOAD SOURCE CODE

Hope this helps. Thanks.