3

I'm creating a CMS for my client to work with his photographs and to sell them on his site. For the CMS end as well as the front end, which both will be all AJAX, it'd be nice to get a JSON feed setup so that I can just use the same feed to generate new "pages" and "views" with JS.

So this example feed would have like {[name:'A Photo',description:'lorem ipsum...'],[...]} and then with jQuery or JS i can create a table of all his photographs, pages, etc. How can I set this up for myself?

Should I just create a PHP file that gets all the data from the MongoDB put's it in an array than convert the array to JSON?

hakre
  • 193,403
  • 52
  • 435
  • 836
Oscar Godson
  • 31,662
  • 41
  • 121
  • 201

3 Answers3

9
    $cursor = $this->collection->find($params);
    $return = array();
    $i=0;
    while( $cursor->hasNext() )
    {

        $return[$i] = $cursor->getNext();
        // key() function returns the records '_id'
        $return[$i++]['_id'] = $cursor->key();
    }
    return json_encode($return);

That is how I return JSON frrom Mongo.

Stefan
  • 1,486
  • 2
  • 13
  • 19
Gazler
  • 83,029
  • 18
  • 279
  • 245
  • Awesome, i'll have to check this when I get home. Seems like it would work. And also, thanks for letting me know that there is a hasNext() function. Still learning the MongoDB PHP driver :) – Oscar Godson Oct 08 '10 at 16:53
  • This seems to work fairly well, but why is it missing some stuff like the _id's and i have a "file" item in my collection with an _id that I stored from GridFS, but that is also not showing up? – Oscar Godson Oct 11 '10 at 04:03
  • Notice: Undefined property: MongoCursor::$key in /var/www/extextures.com/dashboard/functions.php on line 51 -- Is what i get? – Oscar Godson Oct 20 '10 at 08:01
1

I did it this way:

$cursor = $collection->find($params);
if($cursor->hasNext())
{
    return json_encode(iterator_to_array($cursor));
}

If you need the _ids, check this answer to see why you're not getting them: MongoDB PHP: How do I get ObjectId with a JSON feed? (it's blank)

Community
  • 1
  • 1
Jason J. Nathan
  • 7,422
  • 2
  • 26
  • 37
0

This is what I do :

$data = json_decode(json_encode(iterator_to_array($cursor, true)));

this way I make sure I have an array of objects that you can properly call :

foreach($data as $doc){
    echo 'title:'.$doc->title.'<br>';   
}
Eric
  • 9,870
  • 14
  • 66
  • 102