Reading a CSV file in PHP

CSV files have data in the comma separated format. This data format is generally used for importing / exporting data. Reading a CSV file in PHP is very easy and can be be handled in a few lines of code.

The image below shows our same CSV file.

This is the names.csv file screenshot placed in the files folder on server

The below code reads a CSV file named “names.csv” which is placed in the “files” folder on server. Please look at the code carefully and after that read the explanation of each line in the Explanation section.


//Open the file for reading.
$fileHandler = fopen("files/names.csv", "r");

while (  ! feof( $fileHandler )  )

   //Read the file line by line for CSV data.
    $csvLine = fgetcsv( $fileHandler, 1024 );

    //Display data
     echo 'ID: '. $csvLine[0]; echo ' Name: '. $csvLine[1];
     echo ' Email: '.$csvLine[2]; echo ' Address: '.$csvLine[3];

}//End of While loop


Explanation :

First of all we have to read the file, for this PHP is providing built in function. On line number 4 we are reading the names.csv file by using that built in function as followed

 $fileHandler = foepn( "files/names.csv", "r" );

The fopen function takes two arguments, one is the file path and the other is file opening mode. Currently we are opening file only for reading, so we have used “r” mode. For other modes you should read this fopen . fopen returns a file handler if the file is opened successfully, else it returns false. Here our file handler is stored in $fileHandler.

Now the file is opened and we will need to loop through the file line by line and read each individual line. For this purpose we use PHP while loop on line 6 like

 while ( ! feof( $fileHandler ) )  

As the loop goes line by line through the file, when the end of the file is reached we have to stop reading the file. For this purpose we are using a PHP function feop and when the file end is reached it returns false, and the code stop reading the file.

We read each line by PHP function fgetcsv  on line 10 .

 $csvLine = fgetcsv( $fileHandler, 1024 ); 

We are passing two arguments to fgetcsv function. The first argument is required and is our file handler $fileHandler. The second argument we have passed is optional argument and is called length. For more details please read it at fgetcsv . fgetcsv returns a single CSV line in the form of array which is read from our opened file. We are displaying the data on line 13 and 14. Please note that it returns a simple array which index starts from 0, so the ID is at 0, name is at 1, email is at 2 and so on .

What you think? Reading a CSV file in PHP is very easy or difficult?

Latest Content