Skip to content

Instantly share code, notes, and snippets.

@jmikola
Created June 21, 2012 22:24
Show Gist options
  • Save jmikola/2968984 to your computer and use it in GitHub Desktop.
Save jmikola/2968984 to your computer and use it in GitHub Desktop.
Testing bson_decode() and bson_encode() in PHP
<?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]);
<?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