I want to use pagination in php with the use ajax and data are coming from file. while searching a key word the page shows 1st 20 records from a file but now i want next remaining record from file and it should use pagination. Any suggestion please?
$keyword=$_POST['data'];
$file = file_get_contents("http://localhost:8080/searchengine/searchDeals?searchKeyword=".$keyword."");
$output = "[";
$line = 1;
if ( !($fp = fopen($file, "r") ) )
exit("Unable to open the input file.");
while( !feof($fp) && $line <= 20 )
{
if($line != 20){
$output = $output.fgets($fp).",";
}else{
$output = $output.fgets($fp);
}
$line++;
}
fclose($fp);
$output = $output."]";
echo $output;
First you'll need to count the total number of pages. It's floor(number_of_lines_in_file / 20)
.
To switch to different pages you'll have to pass the selected page variable(through $_GET for example) and get lines from $page_number - 1 * 20
to $page_number * 20
. You can either get the lines from the loop or think of something more advanced like using fseek
maybe...
But the easiest approach would probably be using PHP's file()
function instead, which will save the file into an array, and you'll only have to get required portion of lines using array_slice
.