dexter dexter - 2 months ago 7
PHP Question

How to read specific line text with interval using PHP

i want read line in text file, with interval 4 , 4 lines show per page..

if load

domain.com/pages/page2.php

output read line (5,6,7,8)

if load
domain.com/pages/page3.php

output read line (9,10,11,12)

my code

$file1 = basename($_SERVER["SCRIPT_FILENAME"], '.php') ;

$file1 = preg_replace("/.+?(\\d+).*/", "$1", $file1);


$file2 = ($file1 - 1);

$file3 = ($file2 *4);

$file4 = ($file3 + 3 );

function retrieveText($file, $init, $end, $sulfix = '')
{
$i = 1;
$output = '';

$handle = fopen($file, 'r');
while (false === feof($handle) && $i <= $end) {
$data = fgets($handle);

if ($i >= $init) {
$output .= $data . $sulfix;
}
$i++;
}
fclose($handle);

return $output;
}


echo retrieveText('file.txt', $file3, $file4, '<br>');


not work, missing lines

Answer

First of all, I'm gonna advise you to get rid of your REGEX name getter and just have the following format:

domain.com/pages?page=1 domain.com/pages?page=2 domain.com/pages?page=3

So on and so forth. You will be using $_GET['page'] to retrieve the page number.


Now, the way that I'd go with it is to have an array with all the lines of the text and to use the array_slice() function. Something along this should do:

function retrieveText($file, $page, $per_page, $suffix)
{
    $content = file_get_contents($file);
    $array = explode(PHP_EOL, $content);
    $start = --$page * $per_page;
    $lines = array_slice($array, $start, $per_page);
    $output = '';
    foreach ($lines as $line) {
        $output .= $line . $suffix;
    }
    return $output;
}

You should then call this function like this:

$page = $_GET['page'];
$page = $page === null ? 1 : $page;
retrieveText('file.txt', $page, 4, '<br>');
Comments