Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JSON data from php MongoCursor

Tags:

php

mongodb

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?

like image 541
user10 Avatar asked Jan 09 '13 09:01

user10


People also ask

How do I pass JSON data to a PHP script?

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:

How to convert a request to JSON in PHP?

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 ...

How to convert cursor to JSON in Python?

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.

How to handle JSON in PHP?

PHP has some built-in functions to handle JSON. Objects in PHP can be converted into JSON by using the PHP function json_encode():


1 Answers

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.

like image 80
Sammaye Avatar answered Sep 24 '22 01:09

Sammaye