Skip to content

Instantly share code, notes, and snippets.

@muddy-28
Last active July 16, 2016 18:17
Show Gist options
  • Save muddy-28/e54fedc9f4bc84f4a61542c503b1d9d7 to your computer and use it in GitHub Desktop.
Save muddy-28/e54fedc9f4bc84f4a61542c503b1d9d7 to your computer and use it in GitHub Desktop.
Convert a comma separated file into an associated Array | Eagale Solutions
<?php
/**
* Convert a comma separated file into an associated array.
* The first row should contain the array keys.
*
* Function Parameters:
*
* @param string $filename Path to the CSV file
* @param string $delimiter The separator used in the file
* @return array
* @link https://gist.github.com/muddy-28/e54fedc9f4bc84f4a61542c503b1d9d7
* @author Adnan Shafique <http://eagalesoft.com/adnan>
* @copyright Copyright (c) 2016, Adnan Shafique
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
/**
* Example usage
*/
$data_from_csv=csv_to_array('example.csv');
print_r($data_from_csv);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment