0

I make a query to my DB using PHP in the following way:

$foodCategory = $_POST["foodCategory"];
    if($foodCategory == "All") {
        $filter = [];
    } else {
        $filter = ["category" => $foodCategory];
    }
$options = [];
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$query = new MongoDB\Driver\Query($filter, $options);
$rows = $manager->executeQuery('posx.menu', $query);

echo(json_encode($rows));

I don't know why the function echos nothing, and to get it work I have to manually assemble the JSON file in the following way:

echo "[";
foreach ($rows as $document) {
    echo(json_encode($document));
    echo (", ");
}
echo "]";

Obviously, manually assembling JSON is not a good idea, therefore I decided to ask the question. Thanks for the help in advanced.

Riccardo Perego
  • 203
  • 2
  • 9

1 Answers1

0

Try

echo json_encode(iterator_to_array($rows));

[How to return JSON data from php MongoCursor

JsMoreno
  • 93
  • 1
  • 6
  • Sorry, write $row and not $rows. Maybe it work. I advise to you review the link and read this documentation [MongoDB Driver](https://www.php.net/manual/es/class.mongodb-driver-query.php) – JsMoreno Apr 10 '20 at 18:38