Question

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!

Was it helpful?

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

OTHER TIPS

The last call of fgetcsv returns boolean (false) result. When you're trying to count it you're getting 1.

I'd replace it with PHP file function:

$lines = file("widgets.csv");

foreach ($lines as $line) {

   $line_of_text = str_getcsv($line);

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

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top