bcncommerce / json-stream
一组用于在PHP中处理JSON的工具
0.4.2
2021-01-12 11:38 UTC
Requires
- php: >=7.3
- ext-json: *
Requires (Dev)
- bcncommerce/stream-wrapper: dev-master
- phpunit/phpunit: ^9.5
- symfony/yaml: ^5.2
README
此项目是对几个非常优秀的PHP JSON库的重写和分支
- salsify/jsonstreamingparser - Json Stream Parser
- rayward/json-stream - Json Stream Writer
JSON Writer
以下是一个使用JSON Writer导出产品目录的示例
$fh = fopen($filename, "w"); $writer = new Writer($fh); $writer->enter(Writer::TYPE_OBJECT); // enter root object $writer->write("catalog", $catalog['id']); // write key-value entry $writer->enter("items", Writer::TYPE_ARRAY); // enter items array foreach($catalog['products'] as $product) { $writer->write(null, array( // write an array item 'sku' => $product['sku'], 'name' => $product['name'] )); } $writer->leave(); // leave items array $writer->leave(); // leave root object fclose($fh);
输出
{"catalog":19,"items":[{"sku":"0001","name":"Product #1"},{"sku":"0002","name":"Product #2"}]}
JSON Reader
使用JSON Reader可以轻松读取上述代码生成的json
$fh = fopen($filename, "r"); $reader = new Reader($fh); $reader->enter(Reader::TYPE_OBJECT); // enter root object $catalog['id'] = $reader->read("catalog"); // read catalog node $reader->enter("items", Reader::TYPE_ARRAY); // enter item array while($product = $reader->read()) { // read product structure $catalog['products'][] = $product; } $reader->leave(); // leave item node $reader->leave(); // leave root object fclose($fh);