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 into our application using multiple methods.
The first method, will read data from file while we can use second method to read data from any variable.
To read CSV file PHP provides fgetcsv() function. This function will read file and check CSV fields.
The fgetcsv() function can required one parameter which is file pointer. There are some other optional arguments which we can use as per our requirements like length for setting maximum length of loop, delimer or encloser. Let's take example for it:
In above example, we have open file into reading mode just like regular file. Then we will use fgetcsv() function and here we have defined limit of 1000 records and it will loop each record. Lastly, we just print data to user.
Here, we also have display row number while looping every time.
The str_getcsv() function is used for reading CSV data from string or variable. Below is syntax for function:
It's' works same as fgetcsv() function where it takes CSV string or variable as required parameter and same optional parameters as previous function. Let's take example for str_getcsv() function:
Here, we have defined CSV data into colors variable and convert that string into array using str_getcsv() function. Then simply loop through that array and print it's content.
In this article, we have read CSV data from file as well as from string variable using in-built PHP functions fgetcsv() and str_getcsv() function. In practical use, we can use this functionality to import data to database or store and display data from CSV files to user.
Ask anything about this examples