-1

the problem is simple but complicated at the same time. feof doesn't print my last word. It take from file name city and code (Venice,A908) and should show in OUTPUT: nameCity,codeOfCity. Let me show you an example:

City.csv

Abano Terme,A001
Abbadia Cerreto,A004
Abbadia Lariana,A005
Abbiategrasso,A010
Zubiena,M196
Zuccarello,M197
Zuclo,M198
Zungri,M204

Code:

<?php
$buffer = "";
$file = fopen("City.csv", "r");

//while (($c = fgetc($file)) != EOF )
//while (($c = fgetc($file)) != NULL )
//while (($c = fgetc($file)) !== false )
while(!feof($file)) 
{       
    $c = fgetc($file);
    $buffer .= $c;

    if($c == ",")
    {
        echo $buffer;       
        $buffer = "";
    }

    if($c == "\n")
    {           
        echo $buffer."<br/>";

        $buffer = "";
    }           
}

fclose($file);
?>

OUTPUT:

Abano Terme,A001 
Abbadia Cerreto,A004 
Abbadia Lariana,A005 
Abbiategrasso,A010 
Zubiena,M196 
Zuccarello,M197 
Zuclo,M198 
Zungri,

2 Answers2

1

Since it seems like you are just trying to output the file as is, with only change being to substitute HTML line breaks <br /> instead of new line characters why not simplify things?

echo nl2br(file_get_contents('City.csv'), true);

Or if you don't want to read the whole file into memory:

$file = fopen('City.csv', 'r');
while(!feof($file)) {       
    echo nl2br(fgets($file), true);
}
fclose($file);

In one of the comments above you mention that you want the city and city values available as variables (though your code example doesn't seem to indicate this). If that is the case, try fgetcsv() like this:

$file = fopen('City.csv', 'r');
while($values = fgetcsv($file)) {
    $city = $values[0];
    $city_code = $values[1];
    echo $city . ',' . $city_code . '<br />';
}
fclose($file);
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
0

Your problem is, there's no newline at the end of your file, so it never hits the last "\n" check to output the buffer contents.

to fix this, you just need to put in another check on that conditional. change

if($c == "\n")

to:

if($c == "\n" || feof($file))

Here's a much cleaner and more concise version of your code if you'd like to use the correct function for parsing a csv file:

<?php
$buffer = array();
$file = fopen("City.csv", "r");
while(!feof($file) && $buffer[] = fgetcsv($file));
fclose($file);
foreach($buffer as $line){
    echo join(',', $line).'<br/>';
}
?>
iam-decoder
  • 2,554
  • 1
  • 13
  • 28