How to read CSV file in PHP

Character Separated Values(CSV) or Comma Separated Values is a file type containing plain text content with a comma or a character as separators. PHP provides in-built functionality to read CSV file.

Here, we will learn to use CSV data in our application using multiple methods.

  1. Read CSV File using PHP fgetcsv()
  2. PHP CSV String Data Read

The first method will read data from file while we can use second method to read data from any variable.

Read CSV File using PHP fgetcsv()

To read CSV file PHP provides fgetcsv() function. This function will read file and check CSV fields.

The fgetcsv() function can require one parameter which is file pointer. There are some other optional arguments that we can use as per our requirements like the length for setting maximum length of loop, delimer or encloser. Let's take an example for it:

<?php
    $row = 1;
    if (($handle = fopen("FILE_NAME.csv", "r")) !== FALSE) {
       while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
          $num = count($data);
          echo "<p> $num fields in line $row: <br /></p>\n";
          $row++;
          for ($i=0; $i < $num; $i++) {
             echo $data[$i] . "<br />\n";
          }
       }
       fclose($handle);
    }
?>

In above example, we have open file in reading mode just like a regular file. Then we will use fgetcsv() function and here we have a defined limit of 1000 records and it will loop each record. Lastly, we just print data to a user.

Here, we also have displayed row numbers while looping every time.

PHP CSV String Data Read

The str_getcsv() function is used for reading CSV data from string or variable. Below is syntax for function:

str_getcsv($csv_string,$separator,$enclosure,$escape_character)

It's' works same as fgetcsv() function where it takes CSV string or variable as a required parameter and same optional parameters as previous function. Let's take an example for str_getcsv() function:

<?php
    $colors = '"RED","#D62433"
    "ORANDE","#FEB635"
    "YELLOW","#FEE492"
    "GREEN","#9BA207"
    "BROWN","#922E2F"';

    $data = str_getcsv($str_CSV, "\n");
    $length = count($data);
    for($i = 0; $i < $length; $i++) {
        $data = str_getcsv($data[$i], ",");
        print_r($data);
    }
?>

Here, we have defined CSV data into colors variable and converted that string into an array using str_getcsv() function. Then simply loop through that array and print it's content.

Conclusion

In this article, we have read CSV data from file as well as from string variables using in-built PHP functions fgetcsv() and str_getcsv() function. In practical use, we can use this functionality to import data to a database or store and display data from CSV files to the user.