views:

34

answers:

2

I'm storing a file through GridFS and saving the id like so:

$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 terminal and doing find() "file" returns: ObjectId("4cbe9afe460890b774110000")

If i do this to create a JSON feed so i can get info back for my application "file" is blank... 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, to me, is why can I do:

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

and get it back tho?

Oh, and here 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":{}}]
+2  A: 

Not sure, but maybe

echo json_encode($return, JSON_FORCE_OBJECT);

is what you need to do.

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

utf8_encode($item['file']);

before assigning it to the $return array.

JochenJung
Thanks! The first thing, although not the answer is awesome. I didn't know that existed. Im using that now. And, UTF8 made it work!
Oscar Godson
A: 

MongoIds keep their values tucked away in an invisible field. It has no visible fields, so there's nothing to convert to JSON, hence {}. If you'd like to have json_encode do the "right" thing, vote for http://jira.mongodb.org/browse/PHP-154.

Echoing a MongoId converts it to a string, that's why it behaves differently.

kristina
So, how do I do it? I need to echo it out?
Oscar Godson
Nevermind! But i do wish this worked without having to convert to utf8!
Oscar Godson