PHP: Read Specific Line From File

后端 未结 12 628
天命终不由人
天命终不由人 2020-11-28 08:15

I\'m trying to read a specific line from a text file using php. Here\'s the text file:

foo  
foo2

How would I get the content of the seco

相关标签:
12条回答
  • 2020-11-28 08:50

    I like daggett answer but there is another solution you can get try if your file is not big enough.

    $file = __FILE__; // Let's take the current file just as an example.
    
    $start_line = __LINE__ -1; // The same with the line what we look for. Take the line number where $line variable is declared as the start.
    
    $lines_to_display = 5; // The number of lines to display. Displays only the $start_line if set to 1. If $lines_to_display argument is omitted displays all lines starting from the $start_line.
    
    echo implode('', array_slice(file($file), $start_line, lines_to_display));
    
    0 讨论(0)
  • 2020-11-28 08:53
    $myFile = "4-21-11.txt";
    $fh = fopen($myFile, 'r');
    while(!feof($fh))
    {
        $data[] = fgets($fh);  
        //Do whatever you want with the data in here
        //This feeds the file into an array line by line
    }
    fclose($fh);
    
    0 讨论(0)
  • 2020-11-28 08:53

    Use stream_get_line: stream_get_line — Gets line from stream resource up to a given delimiter Source: http://php.net/manual/en/function.stream-get-line.php

    0 讨论(0)
  • 2020-11-28 08:54

    I would use the SplFileObject class...

    $file = new SplFileObject("filename");
    if (!$file->eof()) {
         $file->seek($lineNumber);
         $contents = $file->current(); // $contents would hold the data from line x
    }
    
    0 讨论(0)
  • 2020-11-28 08:55

    If you wanted to do it that way...

    $line = 0;
    
    while (($buffer = fgets($fh)) !== FALSE) {
       if ($line == 1) {
           // This is the second line.
           break;
       }   
       $line++;
    }
    

    Alternatively, open it with file() and subscript the line with [1].

    0 讨论(0)
  • 2020-11-28 09:00

    If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:

    $text = shell_exec("sed -n '74,159p' path/to/file.log");
    

    This solution is good if your file is large.

    0 讨论(0)
提交回复
热议问题