How to return JSON data from php MongoCursor

I am using PHP to connect to MongoDB. My code is as follows.

// connect $m = new MongoClient($con_string); // connect to a remote host at a given port $db = $m->main; $customers = $db->customer->find(); 

I want to return the $ customers collection as a json document in my HTML. How can i do this?

+7
source share
3 answers

You can do this in two ways:

 echo json_encode(iterator_to_array($customers)); 

or you can manually scroll it:

 foreach($customers as $k => $row){ echo json_encode($row); } 

Each of the MongoDB objects must correctly implement its __toString() methods in order to return a representation of the value.

+15
source

That will work too. And you can also customize your json.

  $arr = array(); foreach($customers as $c) { $temp = array("name" => $c["name"], "phone" => $c["phone"], "address" => $c["address"]); array_push($arr, $temp); } echo json_encode($arr); 
+8
source

Other answers work, but it's good to know that the generated JSON will have the following form (in this example, I use the hypothetical "name" field for your clients):

 { "5587d2c3cd8348455b26feab": { "_id": { "$id": "5587d2c3cd8348455b26feab" }, "name": "Robert" }, "5587d2c3cd8348455b26feac": { "_id": { "$id": "5587d2c3cd8348455b26feac" }, "name": "John" } } 

Therefore, if you do not want Object _id be the key of each of your result objects, you can add the false parameter to iterator_to_array . Your code will look like this:

 echo json_encode(iterator_to_array($customers, false), true); 

This creates the same result as

 $result = Array(); foreach ($customers as $entry) { array_push($result, $entry); } echo json_encode($result, true); 

which is an array of JSON objects

 [ { "_id": { "$id": "5587d2c3cd8348455b26feab" }, "name": "Robert" }, { "_id": { "$id": "5587d2c3cd8348455b26feac" }, "name": "John" } ] 
+3
source

All Articles