Search code examples
phpfgetcsv

Accessing string returned by fgetcsv


I don't know why I'm struggling with this so much but I'm trying to access the string within an array returned by fgetcsv. I have this code:

if(($handle = fopen($path, "r")) !== FALSE)
{
    if(($data = fgetcsv($handle, "\t")) !== FALSE);
    {
        var_dump($data);

        foreach($data as $row)
        {
            list($cc, $pc, $pn, $an1, $ac1, $an2, $ac2, $lat, $lon) = explode(" ", $row);
            var_dump($row);
        }
    }

    fclose($handle);
}

The var_dump of $data yields:

array(1) {
  [0] =>
  string(46) "US        34050   FPO             AA      Erie    029                                 41.0375-111.6789       "
}

The var_dump of $row yields:

string(46) "US  34050   FPO             AA      Erie    029                     41.0375 -111.6789

When I run the program I'm getting an error that says Notice: undefined offset, specifically because of this line:

list($cc, $pc, $pn, $an1, $ac1, $an2, $ac2, $lat, $lon) = explode(" ", $row);

I'm obviously missing something here but I don't know what it is. Can anyone help me out?


Solution

  • The PHP manual shows that you're not passing the correct arguments to fgetcsv():

    array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]]] )
    

    It needs the length before the delimiter.

    The undefined offset is caused by the fact that you give too many parameters to list compared to the result of the explode(). var_export(explode(" ", $row)); would make that apparent.