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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵