Read huge files easily and quickly with Liner

In this article I’m writing about a simple library which does only one thing but really well.

Liner allows to easily and intuitively read (large) files line by line.

Usage

$liner = new Liner('path/to/a/file'); // or SplFileObject instance

// Read the whole file
$liner->read();

// Only the first line
$liner->read(1);

// Only the second line
$liner->read(1, 1);

// Read 100 lines starting with the 6th line
$liner->read(100, 5);

// You can also pass a closure as a third argument to mutate the result without iterating over it
$iHateExclamationMarks = $liner->read(0, 0, function($file, $line) {
    return str_replace('!', '', $line);
});

// almost forgot to mention that you can get the number of lines
$liner->getNumberOfLines();

// and that you can also delegate methods to SplFileObject
$liner->eof();
$liner->rewind();

Why is it useful?

First of all, I tried to make this file reader easy to use.

Second advantage of Liner is its speed and efficiency. It has been tested on a number of huge files including those with more than 5 million rows and proved itself to be a fast and efficient file reader.

It’s also useful when you have to read HUGE CSV files.

Here’s how you can read a CSV file:

$delimiter = ',';
$liner = new Liner('path_to_a_huge.csv');

$csvAsArray = $liner->read(0, 0, function($file, $line) use ($delimiter) {
    return explode($delimiter, $line);
});

Easy, huh?

Please note that I don’t mean that Liner replaces a fully featured CSV reader. For example, the snippet above doesn’t work in a situation like this:

"some, value", "another, value"

Installation

If you want to give it a try, here’s how:

composer require mobileka/liner

And sometimes I find myself looking for the following line:

"mobileka/liner": "1.0.*"

Make sure to give me a star on GitHub if you like it.

https://github.com/mobileka/liner

← Back