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.

<?php

$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);

?>

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <i> <strong> <cite> <em> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <css>, <diff>, <drupal5>, <html>, <javascript>, <php>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.