Question

Trying to use filegetcsv to parse a CSV file and do stuff with it, using the following code found all over the Internet, including the PHP function definition page:

if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        print_r($data);
    }
    fclose($handle);
}

But the code gives me an infinite loop of warnings on the $data = line:

PHP Warning: fgetcsv() expects parameter 1 to be resource, boolean given in...
  1. I know the file I'm opening is a valid file, because if I add a dummy character to the file name I get a different error and no loop.
  2. The file is in a folder with full permissions.
  3. I'm not using a CSV generated by an Excel on Mac (there's a quirky error there)
  4. PHP version 5.1.6, so there should be no problem with the function
  5. I know the file's not too big, or malformed, because I kept shrinking the original file to see if that was a problem and finally just created a custom file in Notepad with nothing more than two lines like:

    Value1A,Value1B,Value1C,Value1D

Still looping and giving no data. Here's the full code I'm working with now (using a variable that's greater than the number of lines so I can prove that it would loop infinitely without actually giving my server an infinite loop)

if ($handle = fopen($_SERVER['DOCUMENT_ROOT'].'/tmp/test-csv-file.csv', 'r') !== FALSE) {
    while ((($data = fgetcsv($handle, 1000, ',')) !== FALSE) && ($row < 10)) {
        print_r($data);
        $row++;
    }
    fclose($handle);
}

So I really have two questions.

1) What could I possibly be overlooking that is causing this loop? I'm half-convinced it's something really "face-palm" simple...

2) Why is the recommended code for this function something that can cause an infinite loop if the file exists but there is some unknown problem? I would have thought the purpose of the !== FALSE and so forth would be to prevent that kind of stuff.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top