Skip to content

Instantly share code, notes, and snippets.

@billhance
Created November 22, 2011 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billhance/1386513 to your computer and use it in GitHub Desktop.
Save billhance/1386513 to your computer and use it in GitHub Desktop.
CSV to Array function
<?php
function csv_to_array($csv,$has_headings=false,$delimiter=',',$enclosure='"',$escape="//",$eol="\n")
{
$headings = null;
$data = array();
$csv = str_getcsv($csv, $eol); // Array containing each line
if(empty($csv[0]))
{
return array();
}
if($has_headings)
{
$headings = str_getcsv($csv[0], $delimiter, $enclosure, $escape);
array_shift($csv); // Remove the heading row and reset keys
}
$count = count($csv);
for($i = 0; $i < $count; $i++)
{
$data[$i] = str_getcsv($csv[$i], $delimiter, $enclosure, $escape);
if(isset($headings))
{
$data[$i] = array_combine($headings, $data[$i]);
}
}
return $data;
}
$csv = <<<EOD
"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"
"1985/01/21","Douglas Adams",0345391802,5.95
"1990/01/12","Douglas Hofstadter",0465026567,9.95
"1998/07/15","Timothy ""The Parser"" Campbell",0968411304,18.99
"1999/12/03","Richard Friedman",0060630353,5.95
"2001/09/19","Karen Armstrong",0345384563,9.95
"2002/06/23","David Jones",0198504691,9.95
"2002/06/23","Julian Jaynes",0618057072,12.50
"2003/09/30","Scott Adams",0740721909,4.95
"2004/10/04","Benjamin Radcliff",0804818088,4.95
"2004/10/04","Randel Helms",0879755725,4.50
EOD;
$arr = csv_to_array($csv,true);
print_r($arr);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment