PHP : Convert CSV data into associative array

Converting CSV data into associative arrays, is very useful, as we could reference the fields directly with fields names, rather than remembering numerical indexes.

Following assumptions have been made in the preparation of the below mentioned script:

  1. First row of the CSV sheet contains, the name of the columns.
  2. The names of columns are assumed in the format as defined in database columns, for e.g. first_name, last_name, etc. rather than “First Name”, “Last Name”, etc.
  3. Comma(,) has been considered the default delimiter in the file
  4. Double-quotes(“…”) has been considered the default enclosure symbol for complex data
  5. Any data returned from the CSV row, should have same number of elements as header elements.

 

function readCSV($csvFile) {
$aryData = array();
$header = NULL;
$handle = fopen($csvFile, "r");
if($handle) {
while (!feof($handle) ) {
$aryCsvData = fgetcsv($handle);
if(!is_array($aryCsvData)) {
continue;
}
if(is_null($header)) {
$header = $aryCsvData;
} elseif (is_array($header) && count($header) == count($aryCsvData)) {
$aryData[] = array_combine($header, $aryCsvData);
}
}
fclose($handle);
}
return $aryData;
}

$csvFile, refers to full path to the CSV file to be read.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s