Created
January 30, 2018 08:21
-
-
Save rseon/e15cb81f7bc1b43eaebc6f503bc915ac to your computer and use it in GitHub Desktop.
[PHP] Read CSV file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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