Search code examples
phpperformancereadfile

Get first and last 100 characters of a text file


I have a text file and within that text file, there are just few lines but contains about 5-10 million characters. I'm using file_get_contents but because it reads the whole file so the performance become very slow and hangs sometimes when executing. Is there a more efficient way to get first and last 100 characters?


Solution

  • try this to get first 100 characters:

    $fp = fopen('test.txt', 'r');
    $data = fread($fp, 100);
    echo $data;
    fclose($fp);
    

    and get last 100 characters:

    $fp = fopen('test.txt', 'r');
    fseek($fp, -100, SEEK_END);
    $data = fread($fp, 100);
    echo $data;
    fclose($fp);