Skip to content

Instantly share code, notes, and snippets.

@pentagonal
Last active January 13, 2020 03:41
Show Gist options
  • Save pentagonal/bb750b901530cc76fc02176fce538515 to your computer and use it in GitHub Desktop.
Save pentagonal/bb750b901530cc76fc02176fce538515 to your computer and use it in GitHub Desktop.
<?php
// file name to put json
$fileName = '/path/to/data.json';
/**
* This just sample stmt
* @var \PDO $pdo
* @var \PDOStatement $stmt
*/
$stmt = $pdo
->query("SELECT * FROM XXXXXXXX");
// do execute
$stmt->execute();
// create socket
$fp = fopen($fileName, 'w+');
// write open square bracket
$dataWritten = fwrite($fp, '[');
// doing db fetch
$isFirst = true;
while($row = $stmt->fetch()) {
// add commas cause this is array
$data = sprintf(
'%s%s',
$isFirst ? '' : ',', // if first do not prepend comma otherwise prepend
json_encode($row, JSON_UNESCAPED_SLASHES) // encode result
);
$isFirst = false;
// append data per query
$dataWritten += fwrite(
$fp,
$data
);
}
// append square bracket as array close increment
$dataWritten += fwrite($fp, ']');
fclose($fp);
// close database cursor
$stmt->closeCursor();
unset($stmt);
printf("Written %d total bytes data on %s.\n", $dataWritten, $fileName);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment