Hongmu Notes
Home Language Notes PHP reads the content of a text file line by line, outputs 100 lines at a time, and supports paginated output.
Language Notes PHP

PHP reads the content of a text file line by line, outputs 100 lines at a time, and supports paginated output.

PHP reads the content of a text file line by line, outputs 100 lines at a time, and supports paginated output.

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);

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

(Adaptive mobile version) Essay Writing Website Template – Beautiful Literature Website Source Code Download – 1047

(Adaptive mobile version) Essay Writing Website Template – Beautiful Literature Website Source Code Download – 1047 Practical Collection pbootcms Template

A PbootCMS website template designed for essay writing and literary content, compatible with both PC and WAP devices. Its fresh and artistic design makes it ideal for students, teachers, or literature enthusiasts to share their essays, compositions, and prose. This template helps you create a healthy, positive, and inspiring literary sharing platform. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn (Related resources...)
👁 37
(Adaptive mobile terminal) domestic service company pbootcms website template parenting cleaning nanny website source download 0337

(Adaptive mobile terminal) domestic service company pbootcms website template parenting cleaning nanny website source download 0337 Practical Collection pbootcms Template

An adaptive mobile phone terminal housekeeping service company and parenting cleaning nanny PbootCMS website template. The design style is warm and professional, suitable for showing the maternity sister-in-law, parenting sister-in-law, nanny and other services. It helps domestic service agencies to show their professional image online and attract new parents' families. Template display, installation instructions Website background: / admin.php account: admin password: admin decompression password: www.4s5.cn...
👁 42
Linux replaces multiple line breaks with a single line break.

Linux replaces multiple line breaks with a single line break. Summary of pitfalls

I ran into this annoying guy who wanted 80 yuan for just a single code change—and he insisted on doing it remotely via Suning. The issue turned out to be a simple PHP backend call problem, so I figured, 'Alright, let's just fix it. 'But after watching me resolve it in just a few minutes, he suddenly demanded that I also modify the frontend page— leaving me completely speechless! Charging for every single issue he raised, yet he insisted on paying for a whole bunch of problems for just one? Does he really think he's some kind of 'tech novice'? I've dealt with this guy many times before; every time I needed to make a change, he'd keep negotiating the price— and I'd...
👁 154
Solution to reinstall msvcp140.dll (dll file missing repair)

Solution to reinstall msvcp140.dll (dll file missing repair) Summary of pitfalls

msvcp140.dll is the default library file for programs compiled with Visual Studio 2010. This DLL can resolve a range of issues that may arise when certain large-scale games or applications fail to run due to the absence of this DLL in the Visual Studio 2010 compilation environment. msvcp140.dll is an essential DLL required for the execution of programs developed with Visual Studio 2010. Many users have encountered difficulties determining how to obtain or install msvcp140.dll...
👁 178
Drilling Rig General Equipment Manufacturing Industry Website Template 0603

Drilling Rig General Equipment Manufacturing Industry Website Template 0603 Practical Collection Yiyou template

An eYouCMS website template designed for the drilling rig and general equipment manufacturing industries. Its professional industrial design style is ideal for showcasing drilling rig products, general equipment, technical specifications, and real-world engineering application cases. This template helps machinery and equipment manufacturing enterprises build a professional online presence and attract customers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS...
👁 57
(Adaptive Mobile Version) Livestock Equipment Website Template | Automated Farming Equipment Website Source Code – 1048

(Adaptive Mobile Version) Livestock Equipment Website Template | Automated Farming Equipment Website Source Code – 1048 Practical Collection pbootcms Template

A PbootCMS website template for livestock farming equipment and automated animal husbandry systems, compatible with both PC and WAP devices. Featuring a professional, tech-oriented design ideal for showcasing livestock equipment, automated farming systems, and technical solutions. This template helps livestock equipment manufacturers showcase their products online and attract farm operators and agricultural clients. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4...
👁 40