Reading a CSV file with PHP.

In this tutorial, we are going to show you how to read a CSV file using PHP. To do this, we will be using PHP’s native fgetcsv function.

Take a look at the following CSV file, which I’ve named example.csv.


Now, let’s read this CSV file using PHP.

//Open the file.
$fileHandle = fopen("example.csv", "r");

//Loop through the CSV rows.
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
    //Dump out the row for the sake of clarity.

The code above is pretty simple.

  1. We open the CSV file using the fopen function.
  2. After that, we loop through each line in the CSV file using the fgetcsv function.
  3. The fgetcsv function will return an array that contains each column value. If you var_dump the $row variable inside the while loop, you will get a clearer view of its structure.
  4. Finally, fgetcsv will return a FALSE value once the end of file has been reached. This will break our while loop.

If you run the above code, you’ll see that the $row variable is an array that contains column data from each line.

The first column is the person’s name, the second column is the person’s home country and the last column represents the person’s age. In the file, these columns are separated by commas. However, PHP’s fgetcsv function will automatically parse each line for you.

In other words, there is no need to manually split the line by using the explode function. PHP will do all of this for you.

Accessing specific columns in the CSV file.

If you look at the example data, you’ll see that there are three columns in each row. This means that the fgetcsv function will “parse” those three columns into the $row array.

For example, if we want to access the person’s country of origin, we can access it like so.

echo $row[1];

Note: We use 1 because PHP arrays start at 0.

In the following example, we will print out each column and line in the CSV file.

//Open the file.
$fileHandle = fopen("example.csv", "r");

//Loop through the CSV rows.
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
    //Print out my column data.
    echo 'Name: ' . $row[0] . '<br>';
    echo 'Country: ' . $row[1] . '<br>';
    echo 'Age: ' . $row[2] . '<br>';
    echo '<br>';

As you can see, each value in the row is accessible via a specific array index. In other words:

  • 0 = Column 1.
  • 1 = Column 2.

And so on.

If you’re still a bit confused by all of this, be sure to save the example data above into a CSV file so that you can play around with it!

Skipping empty lines.

If you come across an array that has one null value, then it means that your CSV file has a blank line in it. To skip over blank lines using PHP, you can do something like this.

//Loop through the CSV file. 
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) { 
    if(count($row) == 1 && empty($row[0])){
        //Blank line detected.

See also: Creating a CSV file with PHP.