Reading CSV File into PHP ARRAY

CSV file to PHP array

A Comma-separated values (CSV) file stores tabular data (numbers and text) in plain-text form. Often it is one record per line seperated by a comma or any other delimeter. The comma , is often used in USA/UK CSV files where Germany often uses a ; instead

This is an example of a simple CSV file that has 4 fields and 2 records (1 per line)

Year,Make,Model,Length
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38

In PHP it is often useful to be able to read a CSV file and access it’s data. That is where the fgetcsv() funtction comes in handy, it will read each line of a CSV file and assign each value into an ARRAY. You can define the separator in the function as well see PHP docs for fgetcsv() for more options and examples.

Here is a simple function that shows how to read our CSV file and return an ARRAY holding the data from the CSV.


<?PHP
function readCSV($csvFile){
	$file_handle = fopen($csvFile, 'r');
	while (!feof($file_handle) ) {
		$line_of_text[] = fgetcsv($file_handle, 1024);
	}
	fclose($file_handle);
	return $line_of_text;
}


// Set path to CSV file
$csvFile = 'test.csv';

$csv = readCSV($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';
?>

// Returns
Array
(
    [0] => Array
        (
            [0] => Year
            [1] => Make
            [2] => Model
            [3] => Length
        )

    [1] => Array
        (
            [0] => 1997
            [1] => Ford
            [2] => E350
            [3] => 2.34
        )

    [2] => Array
        (
            [0] => 2000
            [1] => Mercury
            [2] => Cougar
            [3] => 2.38
        )

)

June 30 2012

Written by

Web-Developer from Central Florida. This blog is my outlet to what I am into at the time. PHP, Javascript, MySQL, OO Practices, Performance, Cool Software and Services, etc... Please subscribe to the RSS feed

  • Aladeen Lababneh

    Good to know, thanks

  • http://sunnyis.me/ Sunny Singh

    Wouldn’t it make more sense to return an array like this?

    Array(
    [0] => Array ( [Year] => 1997 [Make] => Ford [Model] => E350 [Length] => 2.34 )
    [1] => Array ( [Year] => 2000 [Make] => Mercury [Model] => Cougar [Length] => 2.38 )
    )

    • Guest

      fgetcsv doesn’t build an associative array because it can’t assume that the first row is always going to be a “heading”, but you can easily build the above array from the result.

  • xaxan

    i got like this array, why?

    Array
    (
    [0] => Array
    (
    [0] => yesr
    [1] => Make
    [2] => Model
    [3] => Length
    1997
    [4] => Ford
    [5] => E350
    [6] => 2.34
    2000
    [7] => Mercury
    [8] => Cougar
    [9] => 2.38
    )

    )

  • xaxan

    found .. need to sure that file to make ENCODING in UTF8

  • Guðjón Jónsson

    $file = file(‘test.csv’);
    foreach($file as $k)
    $csv[] = explode(‘,’, $k);

    print_r($csv);

    Please enable [code] in Disqus