Skip to content

Instantly share code, notes, and snippets.

@rseon
Created January 30, 2018 08:21
Show Gist options
  • Save rseon/e15cb81f7bc1b43eaebc6f503bc915ac to your computer and use it in GitHub Desktop.
Save rseon/e15cb81f7bc1b43eaebc6f503bc915ac to your computer and use it in GitHub Desktop.
[PHP] Read CSV file
<?php
$file = dirname(__FILE__) . '/fichier.csv';
$datas = [];
// Open the file
if(($handle = fopen($file, 'r')) !== false) {
$i = 0;
$mapping = []; // OPTION 2 only
// Read each line split by ';'.
while(($data = fgetcsv($handle, 0, ';')) !== false) {
// OPTION 1 : get each column by key :
// Skip first line
if($i++ == 0) continue;
// Get the datas
$datas[] = [
'colonne1' => $data[0],
'colonne2' => (int) $data[1],
// etc...
];
// ---------------------------------------------
// OPTION 2 : mapping with column names in the first line
// Mapping
if($i++ == 0) {
$mapping = $data;
continue;
}
$datas = [];
foreach($mapping as $im => $nm) {
$datas[$nm] = $data[$im];
}
// Get the datas
$datas[] = [
'colonne1' => $data['ColumnName1'],
'colonne2' => (int) $data['ColumnName2'],
];
}
// Close the file
fclose($handle);
}
var_dump($datas);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment