使用if语句的PHP fgets

I have to input some codes in a .txt file like this:

  • 34,bryan,ingles,23,25,30,inge,78,Aprobado Normal
  • 20,jorge,math,20,20,20,lic,60,Pasa con lo minimo

now i have to use a php function to show a specific line using a search. i was trying to us a fgets and an If statement to pull it. Like

while(!feof($fp)){$linea=fgets($fp, (if $code==34));echo $linea;}

i need the code. using a $_post to get a specific line from the .txt file if the $_post[codigo] is in .txt file and to show it.

Your file look like a comma-separated-value file so you'd better use fgetcsv.

while (!feof($fp)){
    $linea = fgetcsv($fp);       // gets one line and cut it in each comma ( `,` ).
    if ($linea[0] == '34') {     // [0] access the first comma-separated-value of your line
      echo implode(',', $linea); // displays the line after concataining each element with a `,` 
    }
}

If your CSV contains empty lines, you should do another check (that the first value of your CSV line exists) :

if ((count($linea) > 0) && ($linea[0] == '34')) {

With the CSV approach, you can get each element of your line easily, for your first line :

  • $linea[0] is 34
  • $linea[1] is bryan
  • $linea[2] is ingles
  • $linea[3] is 23
  • $linea[4] is 25
  • $linea[5] is 30
  • $linea[6] is inge
  • $linea[7] is 78
  • $linea[8] is Aprobado Normal