How can I read only parts of text file?

前端 未结 1 1220
暖寄归人
暖寄归人 2021-01-14 06:25

I have a PHP script that works a lot with large text files, mostly log files. The problem is that most of the time I only want a section of it, from one split point to anoth

相关标签:
1条回答
  • 2021-01-14 07:02

    I think you are looking for fseek.

    You will need, however, to format your data in a way that Xth-character is the beginning of the Yth-data. Practically, if every log can have the same length, this may be an efficient way. Otherwise, you will still need to read every single lines to search for it.

    Let's imagine (untested, but only to get you started):

    function getDataFromFile($fileName, $start, $length) {
        $f_handle = fopen($filename, 'r');
        fseek($f_handle, $start);
        $str = fgets($length);
        fclose($f_handle);
        return $str;
    }
    

    Then:

    $fname='myfile.txt';
    $DATA_LENGTH = 50;
    $wanted_data = 12;
    
    $data = getDataFromFile($fname, $DATA_LENGTH*$wanted_data, $DATA_LENGTH);
    

    I hope this helps.

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