PHP

JSON Lines (NDJSON) Stream Reader

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Read newline-delimited JSON (one object per line) as a generator. Each yield gives you the next decoded record without holding the whole file in memory.
PHP
Raw
<?php
function readJsonLines(string $path): Generator {
    $fh = fopen($path, 'r');
    if (!$fh) throw new RuntimeException("Cannot open $path");
    try {
        while (($line = fgets($fh)) !== false) {
            $line = trim($line);
            if ($line === '') continue;
            yield json_decode($line, true, 512, JSON_THROW_ON_ERROR);
        }
    } finally {
        fclose($fh);
    }
}

foreach (readJsonLines('events.jsonl') as $event) {
    if ($event['type'] === 'signup') process($event);
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.