Search code examples
phpfgetcsv

Weird things about the entries get from fgetcsv() method


My php code is listed below, and the CSV file in the example is as simple as below:

Widget1, blue, $10, have stock

Widget2, red, $12, out of stock

Widget3, green, $14

<?PHP

    $file_handle = fopen("widgets.csv", "r");

    while (!feof($file_handle) ) {

        $line_of_text = fgetcsv($file_handle, 1024);

        $counter = count($line_of_text)."<br />";

        echo $counter;

        for($i=0; $i<$counter; $i++){
            echo $line_of_text[$i];
        }

        echo "<br />";

    }

    fclose($file_handle);

?>

When I run the code, I get the following result:

4
Widget1 blue $10 have stock
4
Widget2 red $12 out of stock
3
Widget3 green $14
1

I really could not figure out why there is a '1' at the end? How come the $counter array has one element at the last loop? And also I could not echo the element out using $line_of_text[0].

Anyone knows why this happens? Thanks in advance!


Solution

  • All you need is

    $handle = fopen("log.txt", "r");
    while ( ($data = fgetcsv($handle, 1024)) !== FALSE ) {
        if(!array_filter($data))
            continue;
        $counter = count($data);
        echo "$counter <br />\n";
        echo implode(" ", $data);
        echo "<br />\n";
    }
    fclose($handle);
    

    Output

    4 
    Widget1 blue $10 have stock
    4 
    Widget2 red $12 out of stock
    3 
    Widget3 green $14