Search code examples
phpmongodbbinarybson

BSON encoding with binary data


I m looking for a way to encode in BSON some binary data. as BSON stands for binary json , I tought it was simple.

However when I want to pack some binary data using bson_encode (from mongoDB package PHP)

I get an exception

$data = AD_Dbase::GetSingleRowResult("SELECT ghost_data FROM ghosts WHERE id=1"); // binary data(blob in mysql)

echo bson_encode(array(1,"this is a test",$data));

Exception :

Fatal error: Uncaught exception 'MongoException' with message 'non-utf8 string: 3' in test.php:7 Stack trace: #0 test.php(7): bson_encode(Array) #1 {main} thrown in test.php on line 7 

Any suggestions ?


Solution

  • The BSON spec supports a number of different field types.

    The bson_encode function you are calling is used to serialise data into a BSON document, which must be in UTF-8 format. This is a lower-level function intended for use in drivers.

    If you want to store or retrieve binary data in a field, you should instead use the MongoBinData class.