简体   繁体   中英

php import csv file into database

I have a file which I need to import into my database but I like to import 10 record at a time.

eg I have 100 records in my .csv file so first time it runs it will start from 0 then it will goto 10 and changes the your to domain.com/importfile.php/?start=10

this is the code I use.

$file = fopen($file, "r");
    while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
        $county = new County();
        $county->countrycode = $countrycode;
        $county->code = trim($data[0]);
        $county->var_name = $county->mod_write_check( trim($data[1]) );
        $county->name = trim($data[1]);
        $county->statecode = trim($data[2]);
        $save = $county->save();
    }
    fclose($file);

I would like to know if this can be done.

You could use $seek = ftell($file); ftell documentation and fseek($file, $seek+1) you will need to carry in your session or somewhere else the value of $seek

I would recommend using SplFileObject for deailing with files.

Here's a blog that goes thrugh the basics:

http://hakre.wordpress.com/2010/07/25/parsing-csv-files-with-php-spl-style/

The SplFileObject can easily seek but in combination with limitIterator you can also do:

$csv = new SplFileObject('data.csv');
$csv->setFlags(SplFileObject::READ_CSV);

foreach(new LimitIterator($csv, 0, 500) as $line){
  #save $line
}

Code snippet source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM