fGetCsv only reading first line?

11,869

Solution 1

From the docs:

fgetcsv — Gets line from file pointer and parse for CSV fields

If you want more than one line then you need to call it more than once.

Solution 2

This example is the "Example 2" from w3schools http://www.w3schools.com/php/func_filesystem_fgetcsv.asp

$file = fopen("contacts.csv","r");

while(!feof($file))
  {
  print_r(fgetcsv($file));
  }

fclose($file);

Using the while loop the code iterates through the whole file/all the lines..

Alternatively.. if you do something like that..

print_r(fgetcsv($file));
print_r(fgetcsv($file));
print_r(fgetcsv($file));

It will print only the first 3 lines..

Share:
11,869
THEK
Author by

THEK

Full Stack Web Developer with experience in Typescript, Javascript, HTML, CSS, Stylus, SASS, NodeJS, PHP, Swift and Objective-C. I'll never claim to be an expert. But I'll help where I can.

Updated on June 16, 2022

Comments

  • THEK
    THEK almost 2 years

    I'm trying to use fgetCsv but for some reason it is only reading the first line. Here is the code:

    $fieldseparator = ",";
    $lineseparator = "\r";
    
    
    if(!file_exists($csvFile)) {
        echo "<div id='error'>Cannot find uploaded file. Please try again</div>";
        exit;
    }
    
    $file = fopen($csvFile,"r");
    
    if(!$file) {
        echo "<div id='error'>Error loading CSV file</div>";
        exit;
    }
    
    $size = filesize($csvFile);
    if(!$size) {
        echo "<div id='warning'>File is empty</div>";
        exit;
    }
    
    $query = "";
    $content = fgetcsv($file,$size,$lineseparator);
    
    
    fclose($file);
    
    foreach($content as $data) {
            $values = explode($fieldseparator,$data);
            $query[$i] = "('".implode("','",$values)."')";
    }
    

    This just outputs one line. Here is the CSV file:

    TSE-P01,1,WO47653897,RM,EcoQuiet,1
    TSE-P02,1,WO47653898,RM,EcoQuiet,1
    TSE-P03,1,WO47653899,RM,EcoQuiet,1
    TSE-P04,1,WO47653900,RM,EcoQuiet,1
    TSE-P05,1,WO47653901,RM,EcoQuiet,1
    TSE-P06,1,WO47653902,RM,EcoQuiet,1
    TSE-P07,1,WO47653903,RM,EcoQuiet,1
    TSE-P08,1,WO47653904,RM,EcoQuiet,1
    

    Any ideas why this might be happening?