p1ratrulezzz/json-collection-parser

用于处理包含对象数组的大型JSON文件的流式解析器

1.5.4 2019-03-11 16:35 UTC

This package is auto-updated.

Last update: 2024-09-29 05:28:16 UTC


README

Build Status

Latest Stable Version Total Downloads composer.lock Minimum PHP Version

基于事件的大型JSON集合解析器(占用少量内存)。基于JSON Streaming Parser构建

此包符合PSR-4PSR-1PSR-2规范。如果您发现任何不符合规范的地方,请通过pull request发送补丁。

安装

您需要Composer来安装此包

composer require p1ratrulezzz/json-collection-parser ~1.5

输入数据格式

集合必须是一个对象数组。

[
    {
        "id": 78,
        "title": "Title",
        "dealType": "sale",
        "propertyType": "townhouse",
        "properties": {
            "bedroomsCount": 6,
            "parking": "yes"
        },
        "photos": [
            "1.jpg",
            "2.jpg"
        ]
    },
    {
        "id": 729,
        "dealType": "rent_long",
        "propertyType": "villa"
    },
    {
        "id": 5165,
        "dealType": "rent_short",
        "propertyType": "villa"
    }
]

用法

作为回调函数使用

function processItem(array $item)
{
    is_array($item); //true
    print_r($item);
}

$parser = new \JsonCollectionParser\Parser();
$parser->parse('/path/to/file.json', 'processItem');

作为闭包使用

$items = [];

$parser = new \JsonCollectionParser\Parser();
$parser->parse('/path/to/file.json', function (array $item) use (&$items) {
    $items[] = $item;
});

作为静态方法使用

class ItemProcessor {
    public static function process(array $item)
    {
        is_array($item); //true
        print_r($item);
    }
}

$parser = new \JsonCollectionParser\Parser();
$parser->parse('/path/to/file.json', ['ItemProcessor', 'process']);

作为实例方法使用

class ItemProcessor {
    public function process(array $item)
    {
        is_array($item); //true
        print_r($item);
    }
}

$parser = new \JsonCollectionParser\Parser();
$processor = new \ItemProcessor();
$parser->parse('/path/to/file.json', [$processor, 'process']);

接收对象作为项目

function processItem(\stdClass $item)
{
    is_array($item); //false
    is_object($item); //true
    print_r($item);
}

$parser = new \JsonCollectionParser\Parser();
$parser->parseAsObjects('/path/to/file.json', 'processItem');

将流作为解析器输入

$stream = fopen('/path/to/file.json', 'r');

$parser = new \JsonCollectionParser\Parser();
$parser->parseAsObjects($stream, 'processItem');

支持文件格式

  • .json - 原始JSON格式
  • .gz - GZIP压缩文件(您需要安装zlib PHP扩展)

运行测试

composer test

许可证

此库遵循MIT许可证发布。