Reading specific line of a file in PHP

前端 未结 6 1536
攒了一身酷
攒了一身酷 2020-12-11 05:33

I am working on reading a file in php. I need to read specific lines of the file.

I used this code:

fseek($file_handle,$start);
while (!feof($file_ha         


        
相关标签:
6条回答
  • 2020-12-11 05:53

    Does this work for you?

    $file = "name-of-my-file.txt";
    $lines = file( $file ); 
    echo $lines[67]; // echos line 68 (lines numbers start at 0 (replace 68 with whatever))
    

    You would obviously need to check the lines exists before printing though. Any good?

    0 讨论(0)
  • 2020-12-11 05:54

    You could do like:

    $lines = file($filename); //file in to an array
    echo $lines[1];           //line 2
    

    OR

    $line = 0;
    $fh = fopen($myFile, 'r');
    
    while (($buffer = fgets($fh)) !== FALSE) {
       if ($line == 1) {
           // $buffer is the second line.
           break;
       }   
       $line++;
    }
    
    0 讨论(0)
  • 2020-12-11 05:57

    You could use function file($filename) . This function reads data from the file into array.

    0 讨论(0)
  • 2020-12-11 05:58

    Use SplFileObject::seek

    $file = new SplFileObject('yourfile.txt');
    $file->seek(123); // seek to line 124 (0-based)
    
    0 讨论(0)
  • 2020-12-11 06:05

    Try this,the simplest one

    $buffer=explode("\n",file_get_contents("filename"));//Split data to array for each "\n"
    

    Now the buffer is an array and each array index contain each lines; To get the 5th line

    echo $buffer[4];
    
    0 讨论(0)
  • 2020-12-11 06:12

    You must read from the beginning. But if the file never/rarely changes, you could cache the line offsets somewhere else, perhaps in another file.

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