PHP Functions to Import/Export CSV data

These two function make it very easy to import and export CSV in PHP.

Documentation

CSVEport()

This function has just one argument - the query that returns the necessary data to be exported.

Example: CSVExport("SELECT name,username,email,url FROM User WHERE status=1");

CSVImport()

This will upload a CSV file and import the data into the specified table. This function must have the following arguments...

$table
The name of the table the data must be imported to
$fields
An array of fields that will be used
$csv_fieldname
The name of the CSV file field

Example: CSVImport("User", array('name','username','email','url'), "csv_file");

Code

<?php
//Get the result of the query as a CSV stream.
//http://www.bin-co.com/php/scripts/csv_import_export/
function CSVExport($query) {
    
$sql_csv mysql_query($query) or die("Error: " mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer
    
    
header("Content-type:text/octect-stream");
    
header("Content-Disposition:attachment;filename=data.csv");
    while(
$row mysql_fetch_row($sql_csv)) {
        print 
'"' stripslashes(implode('","',$row)) . "\"\n";
    }
    exit;
}

//Import the contents of a CSV file after uploading it
//http://www.bin-co.com/php/scripts/csv_import_export/
//Aruguments : $table - The name of the table the data must be imported to
//                $fields - An array of fields that will be used
//                $csv_fieldname - The name of the CSV file field
function CSVImport($table$fields$csv_fieldname='csv') {
    if(!
$_FILES[$csv_fieldname]['name']) return;

    
$handle fopen($_FILES[$csv_fieldname]['tmp_name'],'r');
    if(!
$handle) die('Cannot open uploaded file.');

    
$row_count 0;
    
$sql_query "INSERT INTO $table("implode(',',$fields) .") VALUES(";

    
$rows = array();

    
//Read the file as csv
    
while (($data fgetcsv($handle1000",")) !== FALSE) {
        
$row_count++;
        foreach(
$data as $key=>$value) {
            
$data[$key] = "'" addslashes($value) . "'";
        }
        
$rows[] = implode(",",$data);
    }
    
$sql_query .= implode("),("$rows);
    
$sql_query .= ")";
    
fclose($handle);

    if(
count($rows)) { //If some recores  were found,
        //Replace these line with what is appropriate for your DB abstraction layer
        
mysql_query("TRUNCATE TABLE $table") or die("MySQL Error: " mysql_error()); //Delete the existing records
        
mysql_query($sql_query) or die("MySQL Error: " mysql_error()); // and insert the new ones.

        
print 'Successfully imported '.$row_count.' record(s)';
    } else {
        print 
'Cannot import data - no records found.';
    }

Comments

Anonymous at 19 Jan, 2008 12:39
thanks man...very usefl functions..
you saved me from a big problem
Reply to this.
Anonymous at 20 Jan, 2008 11:18
thanks this is very useful
Reply to this.
Anonymous at 25 Nov, 2008 03:58
how data insert in table through after implode data id
Reply to this.
Anonymous at 20 Jan, 2010 12:18
csv export works fine forme, what is the value we have to give in $csv_fieldname='csv' ........[CSVImport($table, $fields, $csv_fieldname='csv')]
Reply to this.
Basant Sharma at 20 Jan, 2010 09:46


The Third parameter will contain the input fieldname

here is an example :

<input type= "file" name="csvfile" value="">


call the function like this.
$field = array('name','email','phone');
$table = $tbl_contact

CSVImport($table, $fields, 'csvfile')


I hope now it will help you.

Best regard.
Basant
Reply to this.
Arun K at 29 Feb, 2008 05:06
The CSV Import/Export code works good!...
Reply to this.
Brad at 15 Mar, 2008 02:00
Wow I think I've struck gold with your functions, thanks.
Reply to this.
Anonymous at 23 Mar, 2008 04:33
what is an array of fields? are you talking about the header rows/mysql table row names?

Reply to this.
Anonymous at 02 Apr, 2008 05:29
yep! that done the job! nice work!
Reply to this.
Anonymous at 29 Apr, 2008 12:17
Wow very usefl functions thanks
Reply to this.
tulsi at 12 May, 2008 11:54
Thanks for your great functions
Reply to this.
Anonymous at 10 Jun, 2008 04:41
Wow!
Both Are working nice...
Reply to this.
kris at 18 Jun, 2008 02:31
Thanks for the function...BUT in the csv file i obtained for my table , each field is given out twice...lie 1,1,'hi','hi' instead of 1,'hi'. Can you please help me on it.
Reply to this.
Anonymous at 19 Nov, 2008 03:39
I get each field twice too, anybody know why?
Reply to this.
Bob Jones at 20 Jun, 2008 06:48
Simple and functional. Saved me the time. Thanks!
Reply to this.
Anonymous at 30 Jun, 2008 12:18
Wow!
It's good and help me too much.
Thanks.

I trouble with only one problem that how can I shown header whenever exports functionality doing?
Reply to this.
Bob Jones at 10 Jul, 2008 04:52
May I advise two things:
1) prevent SQL Injection attacks with mysql_real_escape_string()
2) try to enter empty values as NULL, rather than empty (so that mysql will error correctly on non-populated fields that should be populated)

To do these, I would change your line:
$data[$key] = "'" . addslashes($value) . "'";
to:
$data[$key] = $value ? "'".mysql_real_escape_string( $value )."'" : "NULL" ;
Reply to this.
Bob Jones at 10 Jul, 2008 05:06
Also, to grab the header row of the file, use $head_row = fgets( $handle ); right after the fopen(). To exclude it from import, shift it off the array just before adding it to the sql_query like this:

array_shift( $rows );
// Then continue with:
$sql_query .= implode("),(", $rows);
Reply to this.
Anonymous at 16 Jul, 2008 01:06
That is some awesome code, thank you guys! This has really hepled me.
Bob, your post about the header was just what I was looking for!
Reply to this.
Anonymous at 16 Jul, 2008 01:08
Thank you for your help, the code, I found it very useful!
Also, thanks Bob Jones for your posts, they were just what I was looking for!

On A Side Note, I could not get your "array_shift($rows);" to work properly, but my script seems to work without shifting the array.
Reply to this.
Anonymous at 16 Jul, 2008 01:10
Thank you for the use of your code, found it very useful! Worked like a charm!

And thank you Bob Jones for your posts on the header managment and SQL Injection prevention.
Reply to this.
kerala properties at 18 Jul, 2008 12:52
Wow!
Both Are working nice...
Reply to this.
Anonymous at 05 Aug, 2008 10:34
New to PHP, but in the example you say >>CSVImport("User", array('name','username','email','url'), "csv_file");

do i replace my user and array value in the argument list? If so, how does the $sql_query variable know what $table is?
Reply to this.
Anonymous at 15 Aug, 2008 10:37
hi,

what must i give in by "csv_file" ???
can you help me and can you give an example ?

thanks
Reply to this.
youshrin at 20 Aug, 2008 03:52
nice function..very quickly adapted..
godd !!:)
Reply to this.
Matt at 26 Feb, 2009 03:13
This is great. How about security? can it be injected with sql queries?
Reply to this.
ST at 02 Mar, 2009 03:32
Hi,
this is nice.
Can you give please give a sample code for using these functions in a HTML page so that the CSV file can be read(for import)/saved(for export) on the client machine's hard drive (via file selection dialog) ?

thanks in advance.

Reply to this.
shiv at 22 Mar, 2009 01:20
Thnaks ......very nice.
Reply to this.
Anonymous at 24 Mar, 2009 02:46
I have a spreadsheet with images, and related clickable links - can I combine the two with this and if so - how? Can I see some example code - I am not a coder but need to get this done.

thanks for any help or advice

Mark
Reply to this.
dion at 16 Aug, 2009 09:31

What is the meaning of this comment ?
in import function, what the problem...

column count doesn't match value count at row 1


thanks

dion
Reply to this.
Mohan at 04 Sep, 2009 11:35
Hi! this my problem!
which place to dec db name
Reply to this.
Naveen Parth at 21 Nov, 2009 06:39
Thx a lot. I was looking for something like these functions.
Reply to this.
pablobablo at 02 Mar, 2010 08:30
Thank you for your help!
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed