[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 386
  • Last Modified:

fgetcsv loop returns 1 row to many

I have been using this loop that I pulled from the php.net website:

do (($data = fgetcsv($csv, filesize("./trial_imports/".$file), ",")) !== FALSE) {

//perform actions

But each time it runs, it always runs through one row too many, inserting a blank row into the database.

I tried making it a do/while but got the same results.

I would change it to loop through based on a count I keep up with, but I don't see a countrows function for the csv file. I've been up working on this for a long time, so I'm probably missing something simple.  Maybe someone can think about it while I sleep ;)
1 Solution

while($data = fgetcsv($csv, filesize("./trial_imports/".$file), ",")) {

//perform actions

because the manual says fgetscsv returns false on error or EOF so maybe the !== FALSE doesnt match up with the EOF mark properly?
No, you're right to use !== false, because fgetcsv() can also return a NULL value for an empty line, and I think you don't want your script to stop in this case, but to skip this empty line, right ?
Try this code :

while (($data = fgetcsv($csv, filesize("./trial_imports/".$file), ",")) !== false) { // note: it's while() and not do() ;)
 if (is_null($data)) continue; // skip if line is empty
 //perform actions

Featured Post

Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now