Skip to content

Instantly share code, notes, and snippets.

@edhaase
Last active June 18, 2016 20:53
Show Gist options
  • Save edhaase/63abc8d6c5451bf27a14f477e7827290 to your computer and use it in GitHub Desktop.
Save edhaase/63abc8d6c5451bf27a14f477e7827290 to your computer and use it in GitHub Desktop.
<?php
/**
* Streaming json writer. Call generator to set up,
* file isn't opened until you call send().
*
* Pass objects with send until you're done. You can call send(null) to close
* or let the finally finish up and close out the file at end of execution.
*
* @param string $file - File path to write to
* @param bool $pretty - Pretty print on or off
* @param string $mode - fopen mode, in case you want to append
*
* Usage is simple:
* <code>
* $js = streamToJson('test.json', true);
* $js->send(['a' => 42]);
* $js->send(['b' => 33, 'c' => 5]);
* $js->send(null);
* </code>
*/
function streamToJson($file, $pretty = false, $mode = 'w')
{
$first = true;
$fp = fopen($file, $mode);
fputs($fp, "[\n");
try {
while(($obj = yield) !== null) {
$json = json_encode($obj, (($pretty)?JSON_PRETTY_PRINT:0));
if($first === false)
fputs($fp, ",\n");
fputs($fp, "$json");
$first = false;
}
} finally {
fputs($fp, "\n]");
fclose($fp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment