Properly parse a Mongo cursor to PHP
Basically what I did was this.
return json_encode(iterator_to_array($cursor));
But this created the aforementioned object which is not what I needed.
I solved it in this way.
$i=0; foreach($cursor as $item){ $return[$i] = array( '_id'=>$item['_id'], 'nCode'=>$item['nCode'], 'pId'=>$item['pId'], 'nText'=>$item['nText'], 'longText'=>$item['longText'], 'nStatus'=>$item['nStatus'], 'nVType'=>$item['nVType'], 'pushDate'=>$item['pushDate'], 'updateFlag'=>$item['updateFlag'], 'counter' => $i ); $i++; }
return json_encode($return);
If you result is big in order to save RAM you could try this more efficient method:
function outIterator($iterator, $resultName='results'){ // Efficient MongoCursor Iterator to JSON // instead of encoding the whole result array to json // process each item individually // in order to save memory by not copying the data multiple times //Start Json Output header('Content-Type: application/json'); echo '{' . $resultName . ': [' //Output each item as json if there are results in the iterator if ($iterator->hasNext()){ foreach ($iterator as $item) { echo json_encode ($fixeditem); if ($iterator->hasNext()) echo ', '; } } //end Json output echo ']}';}$results = $db->collection->find();outIterator($results);