https://github.com/sunaoka/ndjson
A PHP library to read and write NDJSON (Newline Delimited JSON) in low memory.
https://github.com/sunaoka/ndjson
ndjson php
Last synced: over 1 year ago
JSON representation
A PHP library to read and write NDJSON (Newline Delimited JSON) in low memory.
- Host: GitHub
- URL: https://github.com/sunaoka/ndjson
- Owner: sunaoka
- License: mit
- Created: 2022-07-08T05:52:02.000Z (almost 4 years ago)
- Default Branch: develop
- Last Pushed: 2024-12-12T09:52:13.000Z (over 1 year ago)
- Last Synced: 2025-03-17T22:08:14.277Z (over 1 year ago)
- Topics: ndjson, php
- Language: PHP
- Homepage: https://packagist.org/packages/sunaoka/ndjson
- Size: 35.2 KB
- Stars: 7
- Watchers: 2
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# NDJSON Reader/Writer for PHP
[](https://packagist.org/packages/sunaoka/ndjson)
[](https://packagist.org/packages/sunaoka/ndjson)
[](composer.json)
[](https://github.com/sunaoka/ndjson/actions/workflows/test.yml)
[](https://codecov.io/gh/sunaoka/ndjson)
---
A PHP library to read and write [NDJSON](https://github.com/ndjson) (Newline Delimited JSON).
Read and write one line at a time to execute with low memory usage.
For better performance, you can also read and write on multiple lines.
## Installation
```bash
composer require sunaoka/ndjson
```
## Usage
### Read
#### Example NDJSON
```json
{"test": "001"}
{"test": "002"}
{"test": "003"}
{"test": "004"}
{"test": "005"}
```
#### Read one line at a time
```php
use Sunaoka\Ndjson\NDJSON;
$ndjson = new NDJSON('/path/to/file.ndjson');
while ($json = $ndjson->readline()) {
var_dump($json);
}
```
```
array(1) {
["test"]=>
string(3) "001"
}
array(1) {
["test"]=>
string(3) "002"
}
array(1) {
["test"]=>
string(3) "003"
}
array(1) {
["test"]=>
string(3) "004"
}
array(1) {
["test"]=>
string(3) "005"
}
```
#### Read 3 lines at a time
```php
use Sunaoka\Ndjson\NDJSON;
$ndjson = new NDJSON('/path/to/file.ndjson');
foreach ($ndjson->readlines(3) as $jsons) {
var_dump($jsons);
}
```
```
array(3) {
[0]=>
array(1) {
["test"]=>
string(3) "001"
}
[1]=>
array(1) {
["test"]=>
string(3) "002"
}
[2]=>
array(1) {
["test"]=>
string(3) "003"
}
}
array(2) {
[0]=>
array(1) {
["test"]=>
string(3) "004"
}
[1]=>
array(1) {
["test"]=>
string(3) "005"
}
}
```
### Write
#### Write one line at a time
```php
use Sunaoka\Ndjson\NDJSON;
$ndjson = new NDJSON('/path/to/file.ndjson');
$ndjson->writeline(['test' => '001']);
$ndjson->writeline(['test' => '002']);
```
```
{"test": "001"}
{"test": "002"}
```
#### Write multiple lines at a time
```php
use Sunaoka\Ndjson\NDJSON;
$ndjson = new NDJSON('/path/to/file.ndjson');
$ndjson->writelines([['test' => '001'], ['test' => '002']]);
```
```
{"test": "001"}
{"test": "002"}
```