php csv to array with header code example

Example 1: php csv to array with header

function parse($file, $separ = ';')
{
    $arrays = array_map(function ($foo) use ($separ) {
        return array_map("trim", str_getcsv($foo, $separ));
    }, file($file, FILE_SKIP_EMPTY_LINES));

    $header = $arrays[0];
    unset($arrays[0]);

    $array_with_keys = [];
    foreach ($arrays as $array) {
        $_array = [];
        foreach ($array as $key => $value) {
            $_array[$header[$key]] = $value;
        }
        $array_with_keys[] = $_array;
    }

    return $array_with_keys;
}

Example 2: csv to array php

$csv = array_map('str_getcsv', file('data.csv'));

Example 3: php csv to array with headers

function parse($filecsv){
  $array = $fields = array(); $i = 0;
  $handle = @fopen($filecsv, "r");
  if ($handle) {
      while (($row = fgetcsv($handle, 4096)) !== false) {
          if (empty($fields)) {
              $fields = $row;
              continue;
          }
          foreach ($row as $k=>$value) {
              $array[$i][$fields[$k]] = $value;
          }
          $i++;
      }
      if (!feof($handle)) {
          return false;
      }
      fclose($handle);
  }
  return $array;
}

Tags:

Misc Example