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"
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);
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
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)
I prefer an associative array 🙂:
Good point, same here, thank you for the comment! 🙏