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)

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

报告相同问题?

悬赏问题

  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了