fgetcsv loop returns 1 row to many

Posted on 2004-11-02
Last Modified: 2008-03-06
I have been using this loop that I pulled from the 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 ;)
Question by:bennybutler
    LVL 1

    Expert Comment


    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?
    LVL 7

    Accepted Solution

    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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Product Review - Android Remix

    Come along for the ride with our Senior Product Manager, Brian Matis, as he reviews the Android Remix.

    The Client Need Led Us to RSS I recently had an investment company ask me how they might notify their constituents about their newsworthy publications.  Probably you would think "Facebook" or "Twitter" but this is an interesting client.  Their cons…
    Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    The viewer will learn how to dynamically set the form action using jQuery.

    913 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now