How to Import CSV File In Your PHP Application


PHP gives an ease when it comes to Import flat data (Data without hierarchical structure). If you are using XML to fetch and store data that is fine but what about the case when your client have excel sheet ready with multiple records to go into database. CSV (Comma Separated Values) format is a good candidate format to import or export your application data.

Importing data from CSV files

Since we have lines of values separated by commas, the easiest way to process them is to parse each line using the PHP explode() function:

Dealing with special characters

This simple solution will not work if you have a comma in a value, like for instance when the column is an address and it has a value is like “North street, 1”.

In such cases, the column value in the CSV file is quoted to indicate that the data between quotes should be read as a single column. To deal with this situation, you can use a specially tailored regular expression or use the PHP fgetcsv() function.

Note that locale settings may affect how fgetcsv() function works. As noted in the PHP manual, if LANG locale setting is for instance “en_US.UTF-8”, files in one-byte encoding are read wrong by this function, so be aware.

Importing CSV data directly into the database

If you are importing data from a CSV file into a MySQL database, you import it directly into a database table. It will be much faster than processing it line by line using PHP. Fortunately, most relational database have tools for the bulk data import from CSV files. Load data command will help you here. For instance, in MySQL you can use LOAD DATA INFILE query statement.

Friendly User Interface to Import CSV Data into a Database

An alternative solution to import CSV data is to use my class Quick CSV Import. This is even more user-friendly alternative to import CSV data into a database consists in using the application “Quick CSV import with visual mapping”. This application helps importing CSV files into a database table allowing to define with CSV file columns are mapped to which columns of the database table. This application can even suggest automatically separator character besides the comma. Following is an example of Quick CSV import

Test CSV File

Now, a working PHP example to use the above Quick CSV import Class and import the CSV File provided above

If you’ve got any thoughts, comments or suggestions for things we could add, leave a comment! Also please Subscribe to our RSS for latest tips, tricks and examples on cutting edge stuff.

2 I like it
0 I don't like it