kodie
9/15/2016 - 8:50 PM

Pulls .CSV file contents into an associative array.

Pulls .CSV file contents into an associative array.

<?php
function csv_to_array($file, $line_length="0", $delimiter=",", $enclosure="\"", $escape="\\") {
  $csv = array();
  $keys = array();
  $row = 0;
  if (($handle = fopen($file, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, $line_length, $delimiter, $enclosure, $escape)) !== FALSE) {
      $num = count($data);
      for ($c=0; $c < $num; $c++) {
        if ($row == 0) {
          $keys[$c] = $data[$c];
        } else {
          $csv[$row-1][$keys[$c]] = $data[$c];
        }
      }
      $row++;
    }
    fclose($handle);
  }
  return $csv;
}

$array = csv_to_array("file.csv");
?>