How to read or parse CSV file in Laravel Application

In this example, we will create a CSV file, read that CSV file from our controller and return CSV data as JSON response in Laravel Application.

What is CSV?

The CSV stands for Comma Separated Values. It's a plain text file which we can use to store information to hard drive. In CSV file, each line of the file is a data record. Each data record can be single or multiple values separated by comma sign.

It's generally used to store table data into file like excel sheets. Student report, action data, or contact numbers are generally exported as CSV file.

For this example, we will use file functions and fgetcsv() function to read CSV file. It will work on all versions of Laravel.

Create CSV file

First of all, let's create CSV file into our file system or you can use any existing file for this example. We will create new CSV file.

Just copy paste above content into text-editor and save as employees.csv at public folder. You can use any location on your hard drive but you need to specify full path for fill into next steps so we are using application's public folder to store it.

Read CSV File Content

Let's create new controller to handle CSV operation. Enter below command into your terminal :

It will create new file app/Http/Controller/CsvController.php. Let's modify it to read our employee.csv file and return response as JSON data.

First of all, we will open our CSV file using public_path() function in read mode. If files opens successfully then we will loop through file content and create array from file data.

At last, we will return employees data as JSON response.

Display CSV Data

Here, we are just displaying data to user. You can store those data into your database or perform some other login on it. So let's create new route for getting csv data. Open routes/web.php file and modify as below :

Testing CSV File Parsing Functionality

Now, we can test our CSV reading functionality. So first of all run Laravel application server using below command :

Open below URL into browser and it will show CSV file data as JSON response.

CSV Parsed JSON response

Conclusion

Here, we have created a CSV file and read that file into Laravel using in-built PHP functions. It will works on core PHP too but you need to modify some things like giving a full path while reading. Still, if you have any queries feel free to place a comment below.


Share your thoughts

Ask anything about this examples