0

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 ?

Nico AD
  • 1,657
  • 4
  • 31
  • 51
  • Why not use some of the other functionality built into the MongoDB driver? From the documentation: "This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver." http://www.php.net/manual/en/class.mongobindata.php – Brad Jan 03 '14 at 10:33
  • Despite of the weird solution to something I don't understand, the problem is you're not using UTF8 strings, if you don't prepare php to use UTF8 in this enconding I think it won't work. It's a guess bc I'm not sure how bson encoding works in php, I've never needed anything similar :) Try this: http://stackoverflow.com/questions/6987929/preparing-php-application-to-use-with-utf-8 – Maximiliano Rios Jan 03 '14 at 11:21
  • $data is not a string at all, it binary serialized list of float (3 float for a vector x,y,z + a float for time) and the first in in the BLOB is the size of the structure. – Nico AD Jan 04 '14 at 09:17
  • but problem fixed if I use Stennie suggestion above (MongoBinData) – Nico AD Jan 04 '14 at 09:25

1 Answers1

1

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.

Stennie
  • 63,885
  • 14
  • 149
  • 175
  • Thanks Stennie, using new MongoBinData($data) solved the problem. – Nico AD Jan 04 '14 at 09:16
  • please notice that you may have to change the default type of MongoBinData as the PHP lib use the old binary format as default. – Nico AD Jan 17 '14 at 10:45