make FEOF return true sooner to avoid explode() "Undefined offset" error (PHP)

74 Views Asked by At

I have this simple program that print the content of a file

<?php

$fp=fopen("../resources/client.txt","r"); 
$trouve=0;
$cnt=0;
while(!feof($fp)){
    $i=0;
    $cnt++;
    echo "<br>";
    $ligne=fgets($fp);
    $row=explode("|",$ligne);
    while($i<=2){
        echo $row[$i]."|";
        $i++;}
    
}

fclose($fp); ?>

It does the job but after displaying i get also these errors:enter image description here

Is there a simpe solution for this problem? Thank you all in advance.

1

There are 1 best solutions below

0
On

On en empty line you have no $row[1] neither nor $row[2]

<?php

$fp=fopen("../resources/client.txt","r"); 
$trouve=0;
$cnt=0;
while(!feof($fp)){
    $i=0;
    $cnt++;
    echo "<br>";
    $ligne=fgets($fp);
    $row=explode("|",$ligne);
    if (isset($row[$i])) {
        while($i<=2){
            echo $row[$i]."|";
            $i++;
        }
    }
    
}

fclose($fp); ?>