MongoDB PHP: How do I get an ObjectId using a JSON channel? (empty)

I store the file through GridFS and save the id as follows:

$file_id = $gridfs->storeUpload('texture'); $item = array( 'name'=>$_POST['name'], 'description'=>$_POST['description'], 'price'=>$_POST['price'], 'categories'=>$category_array, 'tags'=>$tag_array, 'file'=>$file_id ); $collection->insert($item); 

and through the terminal and the output, find () "file" returns: ObjectId ("4cbe9afe460890b774110000")

If I do this to create a JSON channel, so I can get information for my application. The file is empty ... why is this ?:

 foreach($cursor as $item){ $return[$i] = array( 'name'=>$item['name'], 'description'=>$item['description'], 'file'=>$item['file'] ); $i++; } echo json_encode($return); 

The strange thing for me is why I can do:

 foreach($cursor as $item){ echo $item['file']; } 

and bring it back?

Oh, and this is what the feed returns:

 [{"name":"Tea Stained Paper 1","description":"Grungy paper texture stained with tea and coffee.","file":{}},{"name":"Worn Metal 1","description":"A grooved, worn old metal texture","file":{}}] 
+5
source share
2 answers

Not sure, but maybe

 echo json_encode($return, JSON_FORCE_OBJECT); 

- this is what you need to do.

It may also be that you need to convert $item['file'] to utf8

 utf8_encode($item['file']); 

before assigning it to the $return array.

+5
source

MongoIds keep their values ​​hidden in an invisible field. It has no visible fields, so there is nothing to convert to JSON, therefore {} . If you want json_encode to do the β€œright” thing, vote for http://jira.mongodb.org/browse/PHP-154 .

By repeating MongoId, it converts it to a string, so it behaves differently.

+1
source

Source: https://habr.com/ru/post/904213/


All Articles