Skip to content

Instantly share code, notes, and snippets.

@jgauthi
Last active February 28, 2026 10:26
Show Gist options
  • Select an option

  • Save jgauthi/b7e763aaf97c92b46e18f5d8944d6afc to your computer and use it in GitHub Desktop.

Select an option

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 $key_line = null, string $delimiter = ',', string $enclosure = '"', string $escape = '\\'): array
{
if (!is_readable($file)) {
throw new \InvalidArgumentException("The file {$file} doesn't exists or not readable.");
}
$titles = $content = [];
if (false === ($handle = fopen($file, 'r'))) {
return $content;
}
// Détection et suppression du BOM UTF8
$bom = "\xEF\xBB\xBF";
$firstLine = fgets($handle);
if (str_starts_with($firstLine, $bom)) {
$firstLine = substr($firstLine, 3);
}
// Analyser la première ligne pour les titres
$data = str_getcsv($firstLine, $delimiter, $enclosure, $escape);
foreach ($data as $index => $var) {
$titles[$index] = trim($var);
}
// Intégration du contenu
while (false !== ($data = fgetcsv($handle, 3000, $delimiter, $enclosure, $escape))) {
// Récupérer le contenu
$line = [];
$row_content = 0;
foreach ($data as $index => $var) {
if (!isset($titles[$index])) {
continue;
}
$var = trim($var);
if (empty($var)) {
$line[$titles[$index]] = null;
continue;
}
$line[$titles[$index]] = $var;
$row_content += mb_strlen($var);
}
// Vérifier que la ligne inscrite n'est pas vide
if (!empty($row_content)) {
if (!empty($key_line) && array_key_exists($key_line, $line)) {
$content[$line[$key_line]] = $line;
} else {
$content[] = $line;
}
}
}
fclose($handle);
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment