You have a TXT file containing one million titles, with one title per line. Each time you make a request, you receive a `pageid`; when `pageid` is 1, the first to 100th titles in the file are output; when `pageid` is 2, the 101st to 200th titles are output; and so on. The PHP code is also very simple:
隐藏内容:会员可查看
<?php
// 打开标题文件
$handle = fopen("huizong.txt", "r");
// 读取文件内容,并移除UTF-8 BOM
$content = fread($handle, filesize("huizong.txt"));
$content = substr($content, 3); // 移除UTF-8 BOM
// 关闭文件句柄
fclose($handle);
// 将内容按行分割为数组
$titles = explode("\n", $content);
// 去除每行首尾的空格
$titles = array_map('trim', $titles);
// 获取文件总行数
$total = count($titles);
// 设置每页显示的标题数量和当前页的 pageid
$per_page = 1000;
$page_id = isset($_GET['pageid']) ? intval($_GET['pageid']) : 1;
// 计算总页数
$total_pages = ceil($total / $per_page);
// 计算偏移量
$offset = ($page_id - 1) * $per_page;
// 读取指定偏移量和行数的标题
$titles = array_slice($titles, $offset, $per_page);
// 将标题、总行数、总页数组成关联数组
$data = array(
'total' => $total,
'total_pages' => $total_pages,
'titles' => $titles
);
// 输出标题列表
header('Content-Type: application/json');
echo json_encode($data);
The first approach reads all files at once, which is slightly slower in terms of efficiency; however, it handles 800,000 rows of data quite quickly. The second approach is an optimized version – storing tens of millions of rows of data is no problem:
隐藏内容:会员可查看
<?php
$filename = "huizong.txt";
// 打开标题文件
$handle = fopen($filename, "r");
// 获取文件总行数
$total = count(file($filename));
// 设置每页显示的标题数量和当前页的 pageid
$per_page = 100;
$page_id = isset($_GET['pageid']) ? intval($_GET['pageid']) : 1;
// 计算总页数
$total_pages = ceil($total / $per_page);
// 计算偏移量
$offset = ($page_id - 1) * $per_page;
// 读取指定偏移量和行数的标题
$titles = array();
if ($handle) {
// 跳过偏移量之前的行
for ($i = 0; $i < $offset; ++$i) {
fgets($handle);
}
// 读取指定行数的标题
for ($i = 0; $i < $per_page; ++$i) {
$title = fgets($handle);
if ($title !== false) {
$titles[] = trim($title);
} else {
break;
}
}
fclose($handle);
}
// 将标题、总行数、总页数等信息组成关联数组
$data = array(
'total' => $total,
'total_pages' => $total_pages,
'titles' => $titles
);
// 输出标题列表及相关信息
header('Content-Type: application/json');
echo json_encode($data);