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

)
affiliate_link
Share this Post:
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

Comments are closed.