dtwbp26022 2016-03-23 13:23
浏览 34

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

On the MongoLabs documentation to insert a document the following jQuery code is given in the example: 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..

How do i make a POST request in php to call the MongoLABs data APIS?

How to convert the above jquery code to php code?

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
   $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;
    ?>
  • 写回答

1条回答 默认 最新

  • dongyan4157 2016-03-24 04:32
    关注

    Got the mistake: If anyone has the same issue or want to use the mLabs data api.. Use the following:

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

    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口