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).
1 2 3 | 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:
You have a file exported from Excel or a database, and you want to extract the records and fields into a format you can manipulate in PHP and want to import it in Database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | $fp = fopen('sample.csv','r') or die("can not open file"); while($csv_line = fgetcsv($fp,1024)) { $connection=mysql_connect("localhost","root","mysqldba") or die("Database Path not valid"); mysql_select_db("test",$connection) or die ("Database not found"); $result = mysql_query("insert into person (`firstname`,`lastname`) values ('".$csv_line[0]."','".$csv_line[1]."')"); echo '<tr>'; for ($i = 0, $j = count($csv_line); $i < $j; $i++) { echo '<td>'.$csv_line[$i].'</td>'; } echo "</tr>"; } echo '</table>'; fclose($fp) or die("can not close file"); |
Must READ:
To import user from CSV in WordPress
Parsing a RSS Feed with WordPress
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.
Comments (2)