PHP CSV Files

PHP CSV Files

Last Updated on Mar 21, 2023

Intro

Do you remember working with files? Then let's get started

Read CSV

reading csv is like reading a file but instead of reading the line with fgets we use fgetcsv to read the line

fgetcsv(file, length, separator, enclosure);

File: is the file we have opened

Length: 0 for reading the whole row or you can limit how much of the row it should read

Separator: for csv file the default is comma “,”

Enclosure: for quotes the default is double quotes ‘“‘

/* the csv file looks like this
id,name
1,Amir
2,Pratham
3,Simon
*/
$file = fopen('example.csv','r');
//fgetcsv(file, length, separator, enclosure, escape);
$row = fgetcsv($file);
while($row != false){
    echo $row[0] . '-' . $row[1];
    echo '<br>';
    $row = fgetcsv($file);
}
fclose($file);
/* output is :
id-name
1-Amir
2-Pratham
3-Simon
 */

Write CSV

Like writing to a file but instead of using fwrite we use the fputcsv function. The first arg is the file and the second arg is all the columns of that row as an array.

It will take care of the new line and enclosing the string and everything else. Super easy!

$firstRow = ['id','name'];
$names = [
    ['1','Amir'],
    ['2','Pratham'],
    ['3','Simon'],
];
$file = fopen('example.csv','w');
fputcsv($file,$firstRow);
foreach($names as $name){
    fputcsv($file,$name);
}
fclose($file);

Here writing and reading the file at once

// write to a csv
$firstRow = ['id','name'];
$names = [
    ['1','Amir'],
    ['2','Pratham'],
    ['3','Simon'],
];
$file = fopen('example.csv','w');
fputcsv($file,$firstRow);
foreach($names as $name){
    fputcsv($file,$name);
}
fclose($file);
/* the csv file looks like this
id,name
1,Amir
2,Pratham
3,Simon
*/

// read the csv file
$file = fopen('example.csv','r');
//fgetcsv(file, length, separator, enclosure, escape);
$row = fgetcsv($file);
while($row != false){
    echo $row[0] . '-' . $row[1];
    echo '<br>';
    $row = fgetcsv($file);
}
fclose($file);
/* output is :
id-name
1-Amir
2-Pratham
3-Simon
 */
https://youtu.be/_t8RhQRxHVA

Conclusion

Now you know about working with csv files in PHP.

I recommend you to open a PHP files and try write to a csv file and read the data from the same file.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • what are csv files
  • read csv
  • write csv

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses