fgetcsv only read first line of csv-file (UPDATE: includes solution)

1.2k views Asked by At

i've the following code but it isn't working well. it only reads the first line of the csv-file, why? can anybody help me? i'm frustrated :(

$handle = fopen($_FILES['prof_datei']['tmp_name'], "r");

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $insert_profs_data = $db->prepare("INSERT INTO professoren (name, titel_prof, titel_dr, titel_ing) VALUES (:eins, :zwei, :drei, :vier)");
    $insert_profs_data->bindParam(':eins', $data[0]);
    $insert_profs_data->bindParam(':zwei', $data[1]);
    $insert_profs_data->bindParam(':drei', $data[2]);
    $insert_profs_data->bindParam(':vier', $data[3]);
    $insert_profs_data->execute();
}

fclose($handle);

UPDATE solution: If you're working with mac to execute this code, you should add the following code line before you open the file:

ini_set('auto_detect_line_endings', true);
1

There are 1 answers

0
Arian Acosta On

Posting an answer based on Mark Baker's and johny's comments.

On Mac (OS X) and probably other operating systems that use different line endings, you may set auto_detect_line_endings to true, before reading the file.

ini_set('auto_detect_line_endings', true);
$contents = file('unknowntype.txt');

This should solve the issue of PHP reading only the first line of a file.