[英]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. 我有一个文件需要导入到数据库中,但是我想一次导入10条记录。
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 例如,我的.csv文件中有100条记录,因此第一次运行它将从0开始,然后将其转到10,并将您更改为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);
您可以使用
$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
ftell文档和
fseek($file, $seek+1)
您需要在会话中或其他地方携带$seek
的值
I would recommend using SplFileObject for deailing with files. 我建议使用SplFileObject删除文件。
Here's a blog that goes thrugh the basics: 这是一个基本的博客:
http://hakre.wordpress.com/2010/07/25/parsing-csv-files-with-php-spl-style/ 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: SplFileObject可以轻松查找,但是与limitIterator结合使用,您还可以执行以下操作:
$csv = new SplFileObject('data.csv');
$csv->setFlags(SplFileObject::READ_CSV);
foreach(new LimitIterator($csv, 0, 500) as $line){
#save $line
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.