【问题标题】:Read a line in file txt in PHP [duplicate]在PHP中读取文件txt中的一行[重复]
【发布时间】:2015-06-25 16:13:44
【问题描述】:

我想读取文件文本中的一行。 EX 第 5 行。任何人都可以帮助我吗????

$fp=fopen("test.txt",r)or exit("khong tim thay file can mo");
while(!feof($fp)){
    echo fgets($fp);
}
fclose($fp);

感谢阅读

【问题讨论】:

    标签: php file line readfile requirements.txt


    【解决方案1】:

    您可以使用 fgets() 函数逐行读取文件:

    <?php 
    $handle = fopen("test.txt", "r");
    if ($handle) {
        while (($line = fgets($handle)) !== false) {
            echo $line.'<br/>';
        }
    
        fclose($handle);
    } else {
        // error opening the file.
    } 
    ?>
    

    【讨论】:

      【解决方案2】:

      只需在您的循环中放置一个增量计数器,仅当该计数器与您要求的行号匹配时才回显,然后您可以简单地跳出循环

      $required = 5;
      
      $line = 1;
      $fp=fopen("test.txt",r)or exit("khong tim thay file can mo");
      while(!feof($fp)){
          if ($line == $required) {
              echo fgets($fp);
              break;
          }
          ++$line;
      }
      fclose($fp);
      

      【讨论】:

        【解决方案3】:
        $myFile = "text.txt";
        $lines = file($myFile);//file in to an array
        echo $lines[1]; //line 2
        

        PHP - Reads entire file into an array

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-08-29
          • 2012-09-05
          • 1970-01-01
          • 1970-01-01
          • 2021-11-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多