Load CSV or Delimited Data from a File into a Named Array

This small snippet will allow you to load CSV or other delimited Data from a File into a named array. The heads in the CSV file will be used for the names of the array keys.

$filename = 'myfile.csv';
$delim = ","; // change to \t for tab delimited files

$handle = fopen($filename, "r");
$header = fgetcsv($handle,null,$delim);
while (($data = fgetcsv($handle,null,$delim)) !== FALSE) {
        foreach ($header as $key=>$heading) {
                $heading = trim($heading);
                $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
        }
        // do something with the row
        print_r($row);
}
fclose($handle);

Post new comment

  • Allowed HTML tags: <b> <br> <p> <a> <strong> <cite> <em> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You may use [img:xx] tags to display uploaded files or images inline.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <css>, <diff>, <drupal5>, <html>, <javascript>, <php>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options