PHP code example of sop / json-generator-parser

1. Go to this page and download the library: Download sop/json-generator-parser library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sop / json-generator-parser example snippets


$lines = ... // Generator that produces lines from HTTP SSE stream
$input = (function (Generator $lines): Generator {
    foreach ($lines as $line) {
        // Just an example, no error checking nor validation
        if (!str_starts_with($line, 'data:')) {
            continue;
        }
        $json = trim(substr($line, 5));
        $data = json_decode($json);
        // Yield content delta chunks
        if (!empty($data->choices[0]->delta->content)) {
            yield $data->choices[0]->delta->content;
        }
    }
})($lines);
$listener = new CallbackJSONListener(
    function (array $keys, mixed $value): void {
        // Here you can handle parsed values.
        // Keys contain all structural indices leading to the value.
        // eg. for `{"a":["x","y","z"]}` JSON the second array value would
        // have keys ["a", 1] and value "y"
    }
);
$parser = new JSONGeneratorParser($listener, false);
$parser->parse($input, true);