Sometimes you have data(mainly MySQL data) in comma-separated values (CSV) format. or you have CSV file to import database values and you tried with CSV format from PHPMyAdmin and sometimes its giving error so you need to write some script to import a data So you can go with fgetcsv function.
If the CSV data is in a file or get via a URL so You can open the file with fopen( ) and read in
the data with `fgetcsv()` function in PHP. With the use of fgetcsv(), you can get CSV data in HTML or PHP.fgetcsv() function is to gets line from file pointer(fp) and parsing a CSV fields.
What is fgetcsv:
fgetcsv() function gets file pointer line and parse for CSV fields.This function is similar to fgets () function. fgetcsv() function stops to return to a new line when it reaches the end of the specified length or read the End of the file (EOF).
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = ',' ]] );
First Parameter refers to the file pointer.
The second argument to fgetcsv() is the length of file and it must be longer than the maximum length of a line in your CSV file.length of file is a semi-optional parameter of fgetcsv.
NOTE: Don’t forget to count the end-of-line white-space.
The third argument in fgetcsv() is optional, it’s used when you want to pass different delimiter instead of the comma(,).
Let’s see one example:
$fp = fopen('sample.csv','r') or die("can not open file"); print "
|'.$csv_line[$i].''; } echo "|
You know that is a comma-delimited CSV file is a plain text file consisting of characters, you can use excel to open, the effect is the same as with an xls table.Above example will read the CSV data from sample.CSV file and fetch all data one by one.First connect to MySQL and update record to the database.
Above example give you a basic idea to extract CSV data and import it in the database with Script.