是否可以通过Mongolab的RESTful API在后端使用PHP进行INSERT?

时间:2014-04-07 10:32:25

标签: php mongodb rest

我想将准备好的JSON发送到后端的PHP脚本中,然后使用Mongolab的RESTful API进行插入。我可以找到插入的唯一例子是前端AJAX。

来自 REST API for MongoLab的示例代码。

POST /databases/{database}/collections/{collection}
Content-Type: application/json
Body: <JSON data>

Example (using jQuery):

$.ajax( { url: "https://api.mongolab.com/api/1/databases/my-db/collections/my-coll?apiKey=myAPIKey",
          data: JSON.stringify( { "x" : 1 } ),
          type: "POST",
          contentType: "application/json" } );

不幸的是,我使用的服务器管理员不允许我安装Mongo PHP驱动程序来执行此操作,因此我不得不走这条路。

有人知道这是否可行?

检索数据的示例

$data = file_get_contents('https://api.mongolab.com/api/1/databases/**DATABASE**/collections/**COLLECTION*?q={%22_id%22:{%22$oid%22:%22' . $_GET['id'] . '%22}}&apiKey=**API KEY**');

$obj = json_decode($data);
$obj=$obj[0];

1 个答案:

答案 0 :(得分:2)

翻译成PHP的jQuery示例是:

<?php
$key        = "my API key";
$db         = "my-database-name";
$collection = "my-collection-name";

$document = array(
    "x" => 1,
    "more" => array("data", "here"),
);

$opts = array(
    "http" => array(
        "method"  => "POST",
        "header"  => "Content-type: application/json",
        "content" => json_encode($document),
    ),
);

$context = stream_context_create($opts);

$result = file_get_contents("https://api.mongolab.com/api/1/databases/$db/collections/$collection?apiKey=$key", false, $context);

var_dump($result); // Dumps the response document
?>