### Install JSON Streaming Parser via Composer Source: https://github.com/salsify/jsonstreamingparser/blob/master/README.md Use this command to add the library to your project dependencies. ```bash composer require salsify/json-streaming-parser ``` -------------------------------- ### Custom Email Extractor Listener Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Example of a custom listener extending `IdleListener` to extract email addresses. It identifies emails based on a 'email' key or by validating string values. ```php currentKey = $key; } public function value($value): void { // Check if this is an email field or if value looks like an email if ($this->currentKey === 'email' || (is_string($value) && filter_var($value, FILTER_VALIDATE_EMAIL))) { $this->emails[] = $value; } $this->currentKey = null; } } // Usage $json = '{"users":[{"name":"John","email":"john@example.com"},{"name":"Jane","email":"jane@example.com"}]}'; $stream = fopen('php://temp', 'r+'); fwrite($stream, $json); rewind($stream); $listener = new EmailExtractorListener(); $parser = new Parser($stream, $listener); $parser->parse(); fclose($stream); print_r($listener->emails); // Output: Array ( [0] => john@example.com [1] => jane@example.com ) ``` -------------------------------- ### Run Library Tests Source: https://github.com/salsify/jsonstreamingparser/blob/master/README.md Execute the test suite using the provided make command. ```bash make test ``` -------------------------------- ### Basic JSON Parsing with InMemoryListener Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Demonstrates basic parsing of a JSON file using the `InMemoryListener`. Configure buffer size, line endings, and whitespace emission. Handles parsing exceptions. ```php parse(); fclose($stream); // Get the parsed JSON as PHP array $data = $listener->getJson(); print_r($data); } catch (\JsonStreamingParser\Exception\ParsingException $e) { fclose($stream); // Exception message format: "Parsing error in [line:char]. Message" echo "Parse error: " . $e->getMessage(); } ``` -------------------------------- ### Handling ParsingException in PHP Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Demonstrates catching and extracting line and character position information from a ParsingException when invalid JSON is encountered. ```php parse(); } catch (ParsingException $e) { // Message format: "Parsing error in [line:char]. Description" echo "Error: " . $e->getMessage() . "\n"; // You can parse the message or use the position for error highlighting preg_match('/\[(\d+):(\d+)\]/', $e->getMessage(), $matches); $line = $matches[1] ?? 0; $char = $matches[2] ?? 0; echo "Error at line $line, character $char\n"; } finally { fclose($stream); } // Output: // Error: Parsing error in [1:18]. Start of string expected for object key. Instead got: i // Error at line 1, character 18 ``` -------------------------------- ### Custom JSON Subset Consumption with SubsetConsumerListener Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Extend SubsetConsumerListener to create custom logic for extracting specific data subsets from JSON. Implement the consume() method to define criteria for data selection and handling. ```php dateRanges[] = $data; return true; // Consumed - discard from parent structure } return false; // Not consumed - keep in parent structure } } $json = '{ "report": { "quarters": [ {"startDate": "2024-01-01", "endDate": "2024-03-31", "revenue": 100000}, {"startDate": "2024-04-01", "endDate": "2024-06-30", "revenue": 120000} ] }, "fiscal_year": {"startDate": "2024-01-01", "endDate": "2024-12-31"} }'; $stream = fopen('php://temp', 'r+'); fwrite($stream, $json); rewind($stream); $listener = new DateRangeConsumer(); $parser = new Parser($stream, $listener); $parser->parse(); close($stream); foreach ($listener->dateRanges as $range) { echo "Period: {$range['startDate']} to {$range['endDate']}\n"; } ``` -------------------------------- ### Track parsing position with PositionAwareInterface Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Implement this interface to receive line and character coordinates during the parsing process. Useful for debugging or providing detailed error feedback. ```php line = $lineNumber; $this->char = $charNumber; } public function value($value): void { $this->valuePositions[] = [ 'value' => $value, 'line' => $this->line, 'char' => $this->char ]; } } $json = '{ "name": "Test", "count": 42 }'; $stream = fopen('php://temp', 'r+'); fwrite($stream, $json); rewind($stream); $listener = new PositionTrackingListener(); $parser = new Parser($stream, $listener); $parser->parse(); fclose($stream); foreach ($listener->valuePositions as $pos) { echo "Value '{$pos['value']}' at line {$pos['line']}, char {$pos['char']}\n"; } // Output: // Value 'Test' at line 2, char 18 // Value '42' at line 3, char 14 ``` -------------------------------- ### Parse JSON into memory with InMemoryListener Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Builds a complete PHP array representation of a JSON document. Suitable for smaller documents where memory constraints are not a concern. ```php parse(); fclose($stream); $data = $listener->getJson(); // $data is now a PHP array matching the JSON structure foreach ($data as $product) { echo "{$product['name']}: "."{$product['price']}"; echo $product['in_stock'] ? " (Available)" : " (Out of Stock)"; echo "\n"; } // Output: // Product A: $29.99 (Available) // Product B: $49.99 (Out of Stock) ``` -------------------------------- ### Extract JSON elements with RegexListener Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Matches JSON paths using regex patterns and executes callbacks for specific elements. Supports capture groups to return the matched path. ```php function ($data) { echo "Second person: $data\n"; }, // Get all names using regex (capture group returns path) '(.*/name)' => function ($data, $path) { echo "Found name at $path: $data\n"; }, // Get each array element and access its properties '(/\\d*)' => function ($data, $path) { echo "Person at $path: {$data['name']} ({$data['department']})\n"; } ]); $parser = new Parser($stream, $listener); $parser->parse(); fclose($stream); // Output: // Found name at /0/name: Alice // Second person: Bob // Found name at /1/name: Bob // Found name at /2/name: Charlie // Person at /0: Alice (Engineering) // Person at /1: Bob (Marketing) // Person at /2: Charlie (Engineering) ``` -------------------------------- ### Parse JSON Stream with a Listener Source: https://github.com/salsify/jsonstreamingparser/blob/master/README.md Implement the \JsonStreamingParser\Listener interface and pass it to the parser to process JSON data incrementally. ```php $stream = fopen('doc.json', 'r'); $listener = new YourListener(); try { $parser = new \JsonStreamingParser\Parser($stream, $listener); $parser->parse(); fclose($stream); } catch (Exception $e) { fclose($stream); throw $e; } ``` -------------------------------- ### ListenerInterface Definition Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Defines the contract for JSON event listeners. Implement these methods to handle parsing events like start/end of documents, objects, arrays, keys, and values. ```php parse(); close($stream); echo "Total users processed: $processedCount\n"; ``` -------------------------------- ### Control parsing flow with ParserAwareInterface Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Allows a listener to receive a reference to the parser instance, enabling programmatic control such as stopping the parse operation early. The setParser() method is invoked automatically by the parser. ```php maxItems = $maxItems; } public function setParser(Parser $parser): void { $this->parser = $parser; } public function endObject(): void { $this->itemCount++; if ($this->itemCount >= $this->maxItems && $this->parser) { $this->parser->stop(); } } public function value($value): void { if (is_string($value)) { $this->items[] = $value; } } } // Large array of items $json = '[{"v":"item1"},{"v":"item2"},{"v":"item3"},{"v":"item4"},{"v":"item5"}]'; $stream = fopen('php://temp', 'r+'); fwrite($stream, $json); rewind($stream); $listener = new LimitedItemsListener(3); // Only process first 3 objects $parser = new Parser($stream, $listener); $parser->parse(); fclose($stream); print_r($listener->items); // Output: Array ( [0] => item1 [1] => item2 [2] => item3 ) ``` -------------------------------- ### Process GeoJSON FeatureCollections Efficiently Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Use GeoJsonListener to process large GeoJSON FeatureCollections by handling one Feature at a time. It requires a callback function that is invoked for each Feature. ```php parse(); close($stream); echo "Processed " . count($features) . " features\n"; ``` -------------------------------- ### Recover partial data with CorruptedJsonListener Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Use forceEndDocument() to retrieve successfully parsed data from truncated or malformed JSON streams. This listener is designed to handle parsing exceptions by closing open structures manually. ```php parse(); } catch (\JsonStreamingParser\Exception\ParsingException $e) { // Expected - JSON is incomplete echo "Parse error (expected): " . $e->getMessage() . "\n"; } fclose($stream); // Force close all open structures to recover partial data $listener->forceEndDocument(); // Get whatever was successfully parsed $recoveredData = $listener->getJson(); print_r($recoveredData); // Output: // Parse error (expected): Parsing error in [1:71]. Document must start with object or array. // Array // ( // [users] => Array // ( // [0] => Array // ( // [name] => Alice // [age] => 30 // ) // [1] => Array // ( // [name] => Bob // ) // ) // ) ``` -------------------------------- ### Stop parsing early with ParserAwareInterface Source: https://context7.com/salsify/jsonstreamingparser/llms.txt Terminates the parsing process programmatically once required data is found. Useful for reading metadata from the beginning of large files. ```php setMatch([ '/total_rows' => function ($data) use ($parser, &$totalRows) { $totalRows = $data; echo "Found total_rows: $data\n"; // Stop parsing - we don't need to read the entire file $parser->stop(); } ]); $parser->parse(); fclose($stream); echo "Extracted total: $totalRows\n"; // Output: // Found total_rows: 1000000 // Extracted total: 1000000 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.