halaxa / json-machine

Efficient, easy-to-use, and fast PHP JSON stream parser
Apache License 2.0
1.1k stars 65 forks source link

Provide example when reading JSON from a zip archive #114

Open tacman opened 1 month ago

tacman commented 1 month ago

I think it's possible to use this library when reading directly from a zip file, but I'm not quite sure how. Can you provide an example under the streaming section please?

And again, thanks for this awesome library.

halaxa commented 1 day ago

I'm glad it helps. Just tried asking ChatGPT as I don't have much time to fiddle with it:

use JsonMachine\Items;

$zipFilePath = 'path/to/archive.zip';
$jsonFileInZip = 'data.json';

$zip = new ZipArchive();
if ($zip->open($zipFilePath) === TRUE) {
    $stream = $zip->getStream($jsonFileInZip);
    if ($stream) {
        $jsonItems = Items::fromStream($stream);
        foreach ($jsonItems as $key => $value) {
            echo "Key: $key, Value: ";
            print_r($value);
            echo PHP_EOL;
        }
        fclose($stream);
    } else {
        echo "The JSON file $jsonFileInZip was not found in the ZIP archive.";
    }
    $zip->close();
} else {
    echo "Failed to open the ZIP archive.";
}

Seems ok to me. Should work somewhere along those lines. Can you please give feedback here if it works?