What are CSV files?
A CSV (Comma Separated Values) files are text files, allows data to be saved in a structured format. CSV files can be used with Microsoft Excel, Google Spreadsheets or Open Office Calc kind of tools. These CSV files are saved with .csv extension. In CSV files data fields are usually separated by comma as delimiter, but can also use a tab or pipe symbol instead of comma. CSV files are used to import and export data from application to application. Mostly, the first record is a header containing a list of field names. Any programming language has technique to import and export data from and to database like MS-SQL, MySql, PostGres, etc..
PHP is one of the best programming languages for import and export of the data with the database to and from flat files like CSV files.
Fetching the data from the CSV file
Open the file in the read mode and store the content into variable. We assume that the CSV file contains the information about the contacts having fields firstname, lastname, email, and phone exported and the file name is contacts.csv.
$csvfilehandle = fopen("contacts.csv","r");
Here $csvfilehandle is file pointer to a file "contacts.csv" successfully opened
while (($line = fgetcsv($csvfilehandle,1000,',','"'))!==false){
$data[] = $line;
}
Close the opened file handle with
fclose($csvfilehandle);
The first argument $csvfilehandle is the mandatory arguments and remaining are optional.
1000 is a length of characters per line to be set. This should be greater than the longest line in the file. If you are not sure about the length then don`t specify it.
',' comma is a delimiter you can set or according to the data in the file the delimiter is used.
'"' is the enclosure in the file used for the field value
Now you have all the data of the CSV file into the array $data. If you print this with print_r($data); you get values into array.
Importing data into MySQL table
Now to import the data into the MySQL table named contacts, we need to modify the above wile loop. Let`s do that now.
while (($line = fgetcsv($csvfilehandle,1000,',','"'))!==false){
mysql_query("insert into contacts(
firstname, lastname, email, telephone
)VALUES(
'".mysql_real_escape_string($line[0])."',
'".mysql_real_escape_string($line[1])."',
'".mysql_real_escape_string($line[2])."',
'".mysql_real_escape_string($line[3])."'
)")
or die(mysql_error());
}
fclose($csvfilehandle);
Write me back if you are working for such functionality and not getting through the code.
1 Comment