宫泽 / ndjson
一个用于读取和写入NDJSON(换行分隔的JSON)的PHP库
1.1.5
2024-07-12 01:04 UTC
Requires
- php: ^5.5 || ^7.0 || ^8.0
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0
README
一个用于读取和写入NDJSON(换行分隔的JSON)的PHP库。
一次读取或写入一行,以实现低内存使用。
为了更好的性能,您也可以一次读取或写入多行。
安装
composer require sunaoka/ndjson
用法
读取
示例NDJSON
{"test": "001"} {"test": "002"} {"test": "003"} {"test": "004"} {"test": "005"}
一次读取一行
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"
}
一次读取3行
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"
}
}
写入
一次写入一行
use Sunaoka\Ndjson\NDJSON; $ndjson = new NDJSON('/path/to/file.ndjson'); $ndjson->writeline(['test' => '001']); $ndjson->writeline(['test' => '002']);
{"test": "001"}
{"test": "002"}
一次写入多行
use Sunaoka\Ndjson\NDJSON; $ndjson = new NDJSON('/path/to/file.ndjson'); $ndjson->writelines([['test' => '001'], ['test' => '002']]);
{"test": "001"}
{"test": "002"}