php 读取csv文件入库:
fgetcsv():
array fgetcsv ( int handle [, int length [, string delimiter [, string enclosure]]] )
$row = 1;
$handle = fopen("test.csv","r");
while ($data = fgetcsv($handle, 1000, ",")) {
$num = count($data);
echo "
$num fields in line $row:
/n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "
/n";
}
}
fclose($handle);
?>
或者 一行一行读取 然后分割字符串为数组
$handle=fopen("test.csv","r");
while(!feof($handle)){
$buffer=fgetss($handle,2048);
$data=explode(",",$buffer);
$num=count($data);
for($i=0;$i
print_r($data);
}
}
?>
$csv_file = ROOTPATH . 'logs/reply_summary_2010-08-04-18.csv';
$handle=fopen($csv_file,"r");
$field_data = array('url','pages','start_url','last_url','view','reply','txtid','uids','snatch_time');
$row=1;
while($data=fgetcsv($handle)){
if(!empty ($data) && count($data) == 9){
//判断是否重复url
$this->db_snatch->select('id');
$this->db_snatch->where('url',$data[0]);
if($this->db_snatch->get($this->snatch_info_table)->num_rows() > 0){
continue;
}
$i_data = array_combine($field_data, $data);
$this->db_snatch->insert($this->snatch_info_table,$i_data);
/*
$last_insert_id = $this->db_snatch->insert_id();
if($last_insert_id){
echo '
insert success!id::',$last_insert_id;
}*/
}
$row++;
}
附:
CSV逗号分隔值文件(Comma Separated value),是一种用来存储数据的纯文本文件格式,通常用于电子表格或数据库软件。csv文件,一行即为数据表的一行。
规则 0 开头是不留空,以行为单位。 1 可含或不含列名,含列名则居文件第一行。 2 一行数据不垮行,无空行。 3 以半角符号,作分隔符,列为空也要表达其存在。 4 列内容如存在半角逗号(即,)则用半角引号(即"")将该字段值包含起来。 5 列内容如存在半角引号(即")则应替换成半角双引号("")转义。 6 文件读写时引号,逗号操作规则互逆。 7 内码格式不限,可为ASCII、Unicode或者其他。 CSV文件多用于储存数据,EXCEL文件可以方便地另存为CSV文件。