I’ve got a text file with multiple messages separated by <br/> tags. I need to split them into pages, like search results. So if I have 50 messages, show 10 per page. How can I do this in PHP without a database? The file is basically:
some message <br/>
some message <br/>
...
Any ideas? I’m trying to keep it simple and just use the file.
Topic Summary: Split a text file of messages separated by <br/> into pages with PHP. Read file, explode by <br/>, paginate array (e.g., 10 per page) using simple offset/limit logic. No database needed.
Featured GitHub Resource:
gosfem/Codeigniter-admin-and-user-role-tempate - Codeigniter Admin Template is a Ultimate Codeigniter Material + Bootstrap 4 integrated admin template. We have also added User & Role management … (★ 14)
Topic Overview (Wikipedia):
Pagination, also known as paging, is the process of dividing a document into discrete pages, either electronic pages or printed pages. — Read more on Wikipedia
You can easily do this by reading the file into an array using file() or explode() on the <br/> delimiter. Then use array slicing with offset and limit based on the current page. Here’s a clean modern approach:
No database needed. Works fine for small to medium files. If your file gets huge, consider splitting into multiple files or using a database. Also, make sure the file path is correct and the file is readable.
Roly’s solution is solid. Just a couple of additions:
If you’re dealing with WAP devices, keep the output minimal and avoid heavy HTML. Use plain text or lightweight markup.
For file-based pagination, consider caching the parsed array if the file doesn’t change often. You can serialize the array and store it as a cache file to avoid repeated explode.
If you ever move to a database, use PDO with prepared statements for security. Here’s a quick example of a modern database pagination approach:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
$perPage = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $perPage;
$stmt = $pdo->prepare('SELECT * FROM messages ORDER BY id DESC LIMIT :limit OFFSET :offset');
$stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Then display and add pagination links with total count
?>
But for your WAP text file, go with the first solution. Just test with a small file first. Good luck!