douying6206 2013-03-14 07:33
浏览 17

使用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.

  • 写回答

1条回答 默认 最新

  • duan198123 2013-03-14 07:39
    关注

    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
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)