<?php
function read_csv($csv_file, $index_by = 0, $separator = ';', $rec_len = 1024)
{
$handle = fopen($csv_file, 'r');
if($handle == null || ($data = fgetcsv($handle, $rec_len, $separator)) === false)
{
// Couldn't open/read from CSV file.
return -1;
}
$names = array();
foreach($data as $field)
{
$names[] = trim($field);
}
if(is_int($index_by))
{
if($index_by < 0 || $index_by > count($data))
{
// Index out of bounds.
fclose($handle);
return -2;
}
}
else
{
// If the column to index by is given as a name rather than an integer, then
// determine that named column's integer index in the $names array, because
// the integer index is used, below.
$get_index = array_keys($names, $index_by);
$index_by = $get_index[0];
if(is_null($index_by))
{
// A column name was given (as opposed to an integer index), but the
// name was not found in the first row that was read from the CSV file.
fclose($handle);
return -3;
}
}
$retval = array();
while(($data = fgetcsv($handle, $rec_len, $separator)) !== false)
{
$retval[trim($data[$index_by])] = array_combine($names, $data);
}
fclose($handle);
return $retval;
}
?>