简体   繁体   English

如何调用MongoLabs(mongoDB)RESTFULL APIS在php中添加文档?

[英]How to call the MongoLabs (mongoDB) RESTFULL APIS for adding documents in php?

On the MongoLabs documentation to insert a document the following jQuery code is given in the example: http://docs.mlab.com/data-api/ 在要插入文档的MongoLabs文档上,示例中提供了以下jQuery代码: http ://docs.mlab.com/data-api/

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

I have to call the RESTFULL API end point via PHP for my android app.. 我必须为我的Android应用程序通过PHP调用RESTFULL API端点。

How do i make a POST request in php to call the MongoLABs data APIS? 如何在php中发出POST请求以调用MongoLABs数据API?

How to convert the above jquery code to php code? 如何将上面的jquery代码转换为php代码?

I have tried the following code but no luck. 我尝试了以下代码,但没有运气。 Can someone tell the mistake in the following code or tell how to do it using php? 有人可以在以下代码中告诉错误,还是告诉您如何使用php?

   <?php
   $x=array(
    'x' => 2
);
   $data=json_encode($x);
   echo $data;
   $postdata = $data;


    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );

    $context  = stream_context_create($opts);

    $result = file_get_contents('http://api.mlab.com/api/1/databases/mydb/collections/mycoll?apiKey=xxxxxxxxxxxxxxxxxxxxx', false, $context);

    echo $result;
    ?>

Got the mistake: If anyone has the same issue or want to use the mLabs data api.. Use the following: 弄错了:如果有人遇到相同的问题,或者想使用mLabs数据API。请使用以下命令:

    $x=array(
        'x' => '2'
    );
    $data=json_encode($x);
    //echo $data;

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

    $context  = stream_context_create($opts);

    $result = file_get_contents('https://api.mlab.com/api/1/databases/mydb/collections/mycoll?apiKey=xxxxxxxxxxx', false, $context);

    echo $result;

But try to avoid using the DATA apis as the key is vulnerable and anyone with the key will have access to your entire DB.. 但请尽量避免使用DATA API,因为密钥容易受到攻击,任何拥有密钥的人都可以访问您的整个数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM