How to read and write CSV file with PHP Code Examples in 2022

Summary:

PHP has several built-in functions for reading & writing CSV files. You can use fgetcsv, fputcsv and fopen to read, write and manage csv files. Check out the article for examples and more use cases.

Read and write CSV files in PHP Code Examples

This article explains how to read and write CSV file in PHP through flow diagrams and examples. If you’re already familiar with the basics, you can skip to the examples.

<?php
$employees = [
    ['Id', 'Name', 'Age', 'Salary', 'Department'],
    ['1', 'Anna', '30', 20000, 'Finance'],
    ['2', 'Adam', '25', 15000, 'IT'],
    ['3', 'Bob', '32', 25000, 'Finance'],
    ['4', 'Cara', '20', 12000, 'Logistics'],
    ['5', 'Daniel', '28', 27000, 'Engineering'],
];
 
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
foreach($employees as $employee)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, $employee);
}
 
//Closes the file.
fclose($file);
?>

CSV PHP Code Examples and Learning Path

Introduction

Comma separated file or CSV  is a text-based file that uses a comma as a delimiter. CSV mainly stores tabular data, and the name is inspired by the fact that it uses a comma to separate each data field. The file has several components, including a header, data records and fields. The following image clearly defines these components.

read and write CSV file in php
  • Header – The topmost row that defines a label for a data column.
  • Data record – Each line after the header is a data record.
  • Data field – Each entity separated by a comma is a field.

For consistent data persistence, it is necessary to include the same number of fields in every row. In the case of a missing field, a placeholder like NULL could help avoid confusion while PHP read CSV. Tools like Excel can help visualize a CSV file better than an editor.

read and write CSV file in php

There are built-in functions to read and write CSV files in PHP. The multi-step process of reading or writing a CSV file is explained through the diagram below. These diagrams give an idea of the process flow, and as we dive into the article, we will see relevant functions for every subprocess shown in these diagrams.

PHP write CSV – The Process

Here’s a flow diagram of the PHP write CSV process. 

php write csv

PHP writes CSV starting from opening a new file and then sequentially writing an array of data. 

PHP read CSV – The Process

Here’s a flow diagram of the PHP read CSV process.

php read csv

The process is almost similar to how PHP writes a CSV file. Here PHP repeatedly checks if there are records left for reading.

How to read and write CSV file in PHP?

Now let’s move on to examples of how to read and write CSV file in PHP

Write CSV files in PHP

As we have seen in the diagram already, PHP opens either an existing or a new file. Then, it writes a data array. These two operations are possible with the following two crucial PHP functions.

  • fopen() –   A PHP function that opens a file or URL.
  • fputcsv() – Formats an array as CSV and writes to a file pointer.

PHP writes CSV from an array of employee data using these two functions. Here’s the complete example.

<?php
$employees = [
    ['Id', 'Name', 'Age', 'Salary', 'Department'],
    ['1', 'Anna', '30', 20000, 'Finance'],
    ['2', 'Adam', '25', 15000, 'IT'],
    ['3', 'Bob', '32', 25000, 'Finance'],
    ['4', 'Cara', '20', 12000, 'Logistics'],
    ['5', 'Daniel', '28', 27000, 'Engineering'],
];
 
//Creates a new file employee_records.csv
$file = fopen('employee_records.csv', 'w'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
foreach($employees as $employee)
{
    //Formats the employee record as CSV and writes it out employee_records.csv
    fputcsv($file, $employee);
}
 
//Closes the file.
fclose($file);
?>

So, the fopen function creates a new file, ‘employee_records.csv’. Then the foreach loop iterates over the array. The fputcsv function writes an employee data array to the output CSV file. Finally, the fclose function closes the file. It is good to close a file explicitly as something can go wrong with it if it is left open.

Here’s the output.

Id,Name,Age,Salary,Department
1,Anna,30,20000,Finance
2,Adam,25,15000,IT
3,Bob,32,25000,Finance
4,Cara,20,12000,Logistics
5,Daniel,28,27000,Engineering

Read CSV files in PHP

The diagram above has already shown how PHP reads CSV. The process is almost similar to how PHP writes a CSV file. The only change is that we’ll be using the fgetcsv function, which reads a file line by line.
Here is the CSV file ‘employees.csv’ that PHP will read.

Id,Name,Age,Salary,Department
1,Anna,30,20000,Finance
2,Adam,25,15000,IT
3,Bob,32,25000,Finance
4,Cara,20,12000,Logistics
5,Daniel,28,27000,Engineering
6,Franklin,25,20000,Quality Assurance
7,Gorge,21,15000,IT
8,Kylie,20,10000,Engineering
9,Ivan,23,12000,Logistics
10,James,25,20000,Quality Assurance
<?php
$employees = [];
 
//Creates a new file employee_records.csv
$file = fopen('employees.csv', 'r'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
//As long as there are records in the CSV file.
while(($row = fgetcsv($file)) !== false)
{
    //Push the data record to employees array.
    array_push($employees, $row);
}
 
//Closes the file.
fclose($file);
 
print_r($employees);
?>

The example is almost similar to the write CSV in PHP. The loop fetches data records and pushes them to the employees array. 

Here’s the output.

Array
(
    [0] => Array
        (
            [0] => Id
            [1] => Name
            [2] => Age
            [3] => Salary
            [4] => Department
        )
 
    [1] => Array
        (
            [0] => 1
            [1] => Anna
            [2] => 30
            [3] => 20000
            [4] => Finance
        )
 
    [2] => Array
        (
            [0] => 2
            [1] => Adam
            [2] => 25
            [3] => 15000
            [4] => IT
        )
 
    [3] => Array
        (
            [0] => 3
            [1] => Bob
            [2] => 32
            [3] => 25000
            [4] => Finance
        )
 
    [4] => Array
        (
            [0] => 4
            [1] => Cara
            [2] => 20
            [3] => 12000
            [4] => Logistics
        )
 
    [5] => Array
        (
            [0] => 5
            [1] => Daniel
            [2] => 28
            [3] => 27000
            [4] => Engineering
        )
 
    [6] => Array
        (
            [0] => 6
            [1] => Franklin
            [2] => 25
            [3] => 20000
            [4] => Quality Assurance
        )
 
    [7] => Array
        (
            [0] => 7
            [1] => Gorge
            [2] => 21
            [3] => 15000
            [4] => IT
        )
 
    [8] => Array
        (
            [0] => 8
            [1] => Kylie
            [2] => 20
            [3] => 10000
            [4] => Engineering
        )
 
    [9] => Array
        (
            [0] => 9
            [1] => Ivan
            [2] => 23
            [3] => 12000
            [4] => Logistics
        )
 
    [10] => Array
        (
            [0] => 10
            [1] => James
            [2] => 25
            [3] => 20000
            [4] => Quality Assurance
        )
 
)

Voila! That’s how to read and write CSV file in PHP.

Conclusion

This article provides an in-depth tutorial on how to read and write CSV file in PHP. It includes flow diagrams to create a road map of the reading and writing processes followed by examples. Hopefully, you’ve learned from the ground up, and you can learn more about PHP through similar articles and tutorials at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


© 2022 Confident.Systems