How to Read a CSV File in PHP

09/04/2021

Contents

In this article, you will learn how to read a CSV file in PHP.

PHP fgetcsv() Function

To read a CSV file you can use the fgetcsv() function.

Here is an example:

<?php
  $file = fopen("path/to/file.csv", "r");
  while (($data = fgetcsv($file)) !== FALSE) {
    print_r($data);
  }
  fclose($file);
?>

In this example, fopen() is used to open the CSV file and the “r” parameter specifies that the file should be opened in read mode. The fgetcsv() function is used to read each line of the file, which is stored in the $data variable. The print_r() function is used to print the contents of the $data variable, which will be an array containing the data from the current line of the CSV file. The fclose() function is used to close the file after all lines have been read.

PHP str_getcsv() Function

You can also use the str_getcsv() function to read the content of the csv file and put it into an array. The first parameter is the string of CSV data. The second parameter is the delimiter, which is used to separate the fields in the CSV file. The default delimiter is a comma.

Here is an example:

<?php
  $csv = array_map('str_getcsv', file('path/to/file.csv'));
  print_r($csv);
?>

In this example, file() function is used to read the whole file, and then array_map() function is used to apply str_getcsv() function on each line of the file, which will separate the fields of each line. The resulting array will have the structure where each element of the array represents a row and each element of the row represents a field of that row.

It’s also worth mentioning that you can use libraries like php-csv-parser or league/csv to read and manipulate csv files in more advanced ways.