Created
June 21, 2012 22:24
-
-
Save jmikola/2968984 to your computer and use it in GitHub Desktop.
Testing bson_decode() and bson_encode() in PHP
This file contains 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 | |
// dump.php [database] [collection] [filename] | |
function dump(MongoCollection $collection, $filename) { | |
$file = fopen($filename, 'w'); | |
foreach ($collection->find() as $document) { | |
fwrite($file, bson_encode($document)); | |
} | |
} | |
$m = new Mongo(); | |
$collection = $m->selectCollection($argv[1], $argv[2]); | |
dump($collection, $argv[3]); |
This file contains 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 | |
// parse.php [filename] | |
function parse($filename) { | |
$file = fopen($filename, 'r'); | |
$numObjects = 0; | |
while (true) { | |
$packedLength = fread($file, 4); | |
if (feof($file)) { | |
break; | |
} | |
$unpacked = unpack('V', $packedLength); | |
$length = array_shift($unpacked); | |
fseek($file, -4, SEEK_CUR); | |
$object = bson_decode(fread($file, $length)); | |
echo json_encode($object) . "\n"; | |
++$numObjects; | |
} | |
echo $numObjects . " objects found.\n"; | |
fclose($file); | |
} | |
parse($argv[1]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment