【问题标题】:How to post data to firebase using PHP?如何使用 PHP 将数据发布到 Firebase?
【发布时间】:2016-12-08 15:44:25
【问题描述】:

我正在使用 Laravel 框架并与 Firebase 数据库集成。我尝试将如下数据发布到 Firebase,但它不起作用。

    $url = "https://test.firebaseio.com/test_api/types.json";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);                               
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "id=6");
    $jsonResponse = curl_exec($ch);
    if(curl_errno($ch))
    {
        echo 'Curl error: ' . curl_error($ch);
    }
    curl_close($ch);

我不知道问题出在哪里。而且我也尝试过使用邮递员来做到这一点,它说以下错误。 "error": "Invalid data; couldn't parse JSON object, array, or value. Perhaps you're using invalid characters in your key names."我该如何解决?

【问题讨论】:

    标签: php curl firebase firebase-realtime-database


    【解决方案1】:

    尝试关注一个

        $data = '{"id": "6"}';
    
        $url = "https://test.firebaseio.com/test_api/types.json";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);                               
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
        $jsonResponse = curl_exec($ch);
        if(curl_errno($ch))
        {
            echo 'Curl error: ' . curl_error($ch);
        }
        curl_close($ch);
    

    Firebase 接受 json 对象,您必须将 $data 发布为 json 对象。你可以使用Content-Type: application/x-www-form-urlencoded或Content-Type: text/plain

    【讨论】:

      【解决方案2】:

      id=6 不是有效的 JSON。 {"id":6} 可能就是您的意思。

      试试

      $json='{"id":6}';
          curl_setopt_array($ch, array(
      CURLOPT_POST=>1,
      CURLOPT_HTTPHEADER=>array(
      'Content-Type: application/json',
      'Content-Length: ' . strlen($json)
      ),
      CURLOPT_POSTFIELDS=>$json
      ));
      

      编辑:或者如果站点接受正常的 POST multipart/form-data / application/x-www-form-urlencoded 编码,您可能想要进行 multipart/form-data 编码:

      curl_setopt($ch, CURLOPT_POSTFIELDS, array('id'=>6));
      

      对于应用程序/x-www-form-urlencoded 编码:

      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('id'=>6)));
      

      【讨论】:

      • 谢谢它的工作。问题是 id=6 不是有效的 JSON。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 2014-10-26
      • 2015-07-25
      相关资源
      最近更新 更多