Skip to content

Instantly share code, notes, and snippets.

@samjaninf
Created September 26, 2018 19:44
Show Gist options
  • Save samjaninf/e6202b6c34428136a2532739cffb2595 to your computer and use it in GitHub Desktop.
Save samjaninf/e6202b6c34428136a2532739cffb2595 to your computer and use it in GitHub Desktop.
<?php
// CSV to Array Function
// Copyright (c) 2014-2015, Ink Plant
// https://inkplant.com/code/csv-to-array
// this version was last updated July 20, 2015
ini_set('auto_detect_line_endings',true);
function csv_to_array($file,$args=array()) {
//key => default
$fields = array(
'header_row'=>true, //is there a row of headers before the actual data?
'remove_header_row'=>true, //if there's a header row, this will remove it (after using it)
'numeric_headers'=>false, //if true, ignore the names in the header row and use integers as array keys instead
'trim_headers'=>true, //trim whitespace around header row values
'trim_values'=>true, //trim whitespace around all non-header row values
'debug'=>false, //set to true while testing if you run into troubles
'lb'=>"\n", //line break character
);
foreach ($fields as $key => $default) {
if (array_key_exists($key,$args)) { $$key = $args[$key]; }
else { $$key = $default; }
}
if ($debug) { echo '<p>Opening '.htmlspecialchars($file).'…</p>'; }
$data = array();
$row = 0;
if (($handle = fopen($file,'r')) !== false) {
while (!feof($handle)) {
$line = fgetcsv($handle, 10240);
$num = count($line);
$row++;
if (($header_row) && ($row == 1)) { $data['headers'] = array(); }
else { $data[$row] = array(); }
for ($c=0; $c<$num; $c++) {
$value = $line[$c];
if (($header_row) && ($row == 1)) { //if this is part of the header row
if ($trim_headers) { $value = trim($value); }
if (in_array($value,$data['headers'])) { custom_die('There are duplicate values in the header row: '.htmlspecialchars($value).'.'); }
else { $data['headers'][$c] = (string)$value; }
} elseif (($header_row) && (!$numeric_headers)) { //if this isn't part of the header row, but there is a header row
$key = $data['headers'][$c];
if ($trim_values) { $value = trim($value); }
$data[$row][$key] = $value;
} else { //if there's not a header row at all
if ($trim_values) { $value = trim($value); }
$data[$row][$c] = $value;
}
}
}
fclose($handle);
if ($remove_header_row) { unset($data['headers']); }
if ($debug) { echo '<pre>'.print_r($data,true).'</pre>'; }
return $data;
} else {
custom_die('There was an error opening the file.');
}
}
?>
<?php
//set the location of your CSV file
$file = HOME_DIR.'inkplant.com/population.csv';
//turn that CSV file into an array
$data = csv_to_array($file,array('header_row'=>true));
//now print that array out onto the screen
echo '<pre>'.print_r($data,true).'</pre>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment