I am using PHP to connect with 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 $customers collection as json document to my HTML. How can i do this?
You can simply use the json_encode () function to return JSON response from a PHP script. Also, if you're passing JSON data to a JavaScript program, make sure set the Content-Type header. Let's take a look at an example to understand how it basically works:
PHP File explained: 1 Convert the request into an object, using the PHP function json_decode (). 2 Access the database, and fill an array with the requested data. 3 Add the array to an object, and return the object as JSON using the json_encode () function. More ...
It returns the instance of the Cursor. Converting the Cursor to JSON: Converting the Cursor to the JSON. First, we will convert the Cursor to the list of dictionary. Now, converting the list_cur to the JSON using the method dumps () from bson.json_util You can now save it to the file or can use it in the program using loads () function.
PHP has some built-in functions to handle JSON. Objects in PHP can be converted into JSON by using the PHP function json_encode():
You can do this two ways:
echo json_encode(iterator_to_array($customers));
or you can manually scroll through it:
foreach($customers as $k => $row){
echo json_encode($row);
}
Each of MongoDBs objects should have their __toString()
methods correctly implemented to bring back the representation of the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With