Last active
January 13, 2020 03:41
-
-
Save pentagonal/bb750b901530cc76fc02176fce538515 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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