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 ?

4
  • 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." php.net/manual/en/class.mongobindata.php Commented Jan 3, 2014 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: stackoverflow.com/questions/6987929/… Commented Jan 3, 2014 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. Commented Jan 4, 2014 at 9:17
  • but problem fixed if I use Stennie suggestion above (MongoBinData) Commented Jan 4, 2014 at 9:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Stennie, using new MongoBinData($data) solved the problem.
please notice that you may have to change the default type of MongoBinData as the PHP lib use the old binary format as default.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.