Skip to content

Instantly share code, notes, and snippets.

@jgauthi
Last active March 19, 2021 17:15
Show Gist options
  • Save jgauthi/b7e763aaf97c92b46e18f5d8944d6afc to your computer and use it in GitHub Desktop.
Save jgauthi/b7e763aaf97c92b46e18f5d8944d6afc to your computer and use it in GitHub Desktop.
Convert CSV File to php array
<?php
function csv_to_array(string $file, string $delimiter = ';'): array
{
if (!file_exists($file)) {
throw new InvalidArgumentException("File '{$file}' not found");
}
$titles = $content = [];
if (($handle = fopen($file, 'r')) !== false) {
// Intégration du contenu
while (($data = fgetcsv($handle, 3000, $delimiter)) !== false) {
// Récupérer les titres du CSV (1er ligne du CSV)
if (empty($titles)) {
foreach ($data as $index => $var) {
$titles[$index] = trim($var);
}
continue;
}
// Récupérer le contenu
$line = [];
$row_content = 0;
foreach ($data as $index => $var) {
if (!isset($titles[$index])) {
continue;
}
$var = trim($var);
$line[$titles[$index]] = $var;
$row_content += strlen($var);
}
// Vérifier que la ligne inscrite n'est pas vide
if (!empty($row_content)) {
$content[] = $line;
}
}
fclose($handle);
}
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment