使用php从CSV文件中仅提取3个值

时间:2015-02-18 07:14:58

标签: php csv

我有一个9500行的csv文件,每行有10个值。

我想从每行只向数据库提供3个值。我如何使用PHP实现这一目标。

1,"Goroka","Goroka","Papua New Guinea","GKA","AYGA",-6.081689,145.391881,5282,10,"U","Pacific/Port_Moresby"
2,"Madang","Madang","Papua New Guinea","MAG","AYMD",-5.207083,145.7887,20,10,"U","Pacific/Port_Moresby"
3,"Mount Hagen","Mount Hagen","Papua New Guinea","HGU","AYMH",-5.826789,144.295861,5388,10,"U","Pacific/Port_Moresby"

我只需要将每行的第1,第5和第8个值保存到数据库中。

我试过爆炸每一行,然后从数组中获取每个值并循环遍历每一行。但这需要时间。我正在寻找更好的方法。

1 个答案:

答案 0 :(得分:3)

您可以使用fgetcsv()获取每行数据并在循环中提取所需的值,如下所示:

// setup pdo statement and bind parameters outside of the loop
$field1 = "";
$field2 = "";
$field3 = "";
$pdo_stmt = $db->prepare("INSERT INTO <table> VALUES(?,?,?)");
$pdo_stmt->bind_param(1, $field1, PDO::PARAM_INT);
$pdo_stmt->bind_param(2, $field2, PDO::PARAM_STRING);
$pdo_stmt->bind_param(3, $field3, PDO::PARAM_STRING);

// try to open the csv file containg the data
$fp = fopen("file.csv", "r");

// loop through each row
while($row = fgetcsv($fp) {

  // store field 0, 4 and 7 from each row
  $field1 = $row[0];
  $field2 = $row[4];
  $field3 = $row[7];

  // insert into database
  $pdo_stmt->execute();
}

// close the file
fclose($fp);

当然以上只是作为一个例子,您应该检查,以便真正打开文件,依此类推。如果您正在使用预准备语句,请注意您应准备语句并绑定循环的外部以提高性能。