DEV Community

Discussion on: How to Parse a CSV File in 4 Lines of PHP?

Collapse
 
devtronic profile image
Julian Finkler

I prefer an associative array πŸ™‚:

// open the file in read mode
$file = fopen('data/classic-composers.csv', "r"); 
$headline = null;
// browse each csv line
while (($row = fgetcsv($file)) !== false) {
  if($headline === null) {
    $headline = $row;
    continue;
  }
  $data = array_combine($headline, $row);
  // print the line content
  print_r($data);
}
// close the file
fclose($handle);
Enter fullscreen mode Exit fullscreen mode
Array
(
    [First name] => Carl Philipp Emanuel
    [Last name] => Bach
    [Born] => 8 March 1714
    [Died] => 14 December 1788
)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nidup profile image
Nicolas Dupont

Good point, same here, thank you for the comment! πŸ™