DEV Community

Nicolas Dupont
Nicolas Dupont

Posted on

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

CSV is a standard format to integrate data in applications; when doing so, we often have to import data based on this format. PHP comes with native functions to open a file and parse CSV rows.

Let's take the file classic-composers.csv and its content as an example:

"First name","Last name","Born","Died"
"Carl Philipp Emanuel","Bach","8 March 1714", "14 December 1788"
"Johann","Stamitz","18 June 1717","27 March 1757"
"Joseph","Haydn","31 March 1732","31 May 1809"
"Johann","Christian Bach","September 5, 1735","January 1, 1782"
Enter fullscreen mode Exit fullscreen mode

We can also look at it as a table:

First name Last name Born Died
Carl Philipp Emanuel Bach 8 March 1714 14 December 1788
Johann Stamitz 18 June 1717 27 March 1757
Joseph Haydn 31 March 1732 31 May 1809
Johann Christian Bach September 5, 1735 January 1, 1782

We can parse and display each line using 4 simple lines of PHP code:

// open the file in read mode
$file = fopen('data/classic-composers.csv', "r"); 
// browse each csv line
while (($row = fgetcsv($file)) !== false) {
  // print the line content
 var_dump($row);
}
// close the file
fclose($handle);
Enter fullscreen mode Exit fullscreen mode

Here is the output of the execution:

array(4) {
  [0]=>
  string(10) "First name"
  [1]=>
  string(9) "Last name"
  [2]=>
  string(4) "Born"
  [3]=>
  string(4) "Died"
}
array(4) {
  [0]=>
  string(20) "Carl Philipp Emanuel"
  [1]=>
  string(4) "Bach"
  [2]=>
  string(12) "8 March 1714"
  [3]=>
  string(16) "14 December 1788"
}
// and more lines
Enter fullscreen mode Exit fullscreen mode

That's it for this simple example using native functions!🚀

If you want to go further with CSV manipulation in PHP, you can explore this comprehensive guide on reading and writing CSV files in PHP. It explores modern libraries to parse CSV, explain how to read a one million-line CSV file using a minimum of memory, and share advanced tips and tricks.💡

Top comments (2)

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! 🙏