duanou2016 2014-11-08 15:49
浏览 63
已采纳

在PHP中解析CSV时再读一行

I'm using the following code in PHP to read a CSV file:

  $file = fopen("customers.csv", "r");

  while (!feof($file))
  {
    $rr = fgetcsv($file);
    $name = $rr[0];
    $surname = $rr[1];

    $sql = 'INSERT INTO customer SET ...';
    ...
    $s->execute();
  }
  fclose($file);

The code will insert all the records in the CSV file into customer table, but it tries to insert one line more with NULL values and fails.

How would you correct the code to insert only the number of lines that are in the customers.csv file?

  • 写回答

1条回答 默认 最新

  • douxie3625 2014-11-08 15:53
    关注

    The fgetcsv function will encounter EOF, but you do not exit the loop immediately. Instead you process the row of CSV as normal before checking for EOF in the while condition. Simply add a check for EOF immediately after the call to fgetcsv (and also in the while loop perhaps). But you could also do while (true) {...} and then 'exit' the while loop when you encounter EOF (or if $rr is empty) immediately after fgetcsv function. (Not sure of the php syntax, otherwise I would post exact code, but this logic should work)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?