Search code examples
fgetcsv

Problems with fgetcsv


I have a csv excel file with 2 columns of values: latitudes and longitudes. I need to access each individual latitude and longitude value separately.

But I can't even read the csv file into an array properly. Since I'm using a mac, I started with:

ini_set("auto_detect_line_endings", true);  
$handle = fopen("countlook.csv", "r");
$data = fgetcsv($handle, 100000, ",");

Which returns only the first line (column headings) "Latitude,Longitude" without any actual values.

Not sure where I'm going wrong. Any suggestions would be very welcome.


Solution

  • fgetcsv reads the file line by line, so its important to put it in a loop to get all the data.

    $headers = array();
    $rows = array();
    $c = 0;
    while ($data = fgetcsv($handle, 0, ",")) {
    
            if ($c == 0) {
                $headers = $data;
                
            } else {
                $rows[] = $data;
            }
    
           $c ++;
        }
    fclose($handle);
    

    You should now have the headers in the $headers variable and all the data in the $rows variables.