如何在curl POST请求中进行json查询

时间:2017-03-28 16:48:01

标签: php json curl

我正在尝试将curl POST命令中的以下查询发送到API:

struct Favourite {

var key: String?
let ref: FIRDatabaseReference?
var favourite: Bool?
var currentUserID: String?
var realIndex: Int?
var shortName: String?
let distillery: String?

init(key: String = "", favourite: Bool, currentUserID: String, realIndex: Int, shortName: String, distillery: String){
    self.key = key
    self.ref = nil
    self.favourite = favourite
    self.currentUserID = currentUserID
    self.realIndex = realIndex
    self.shortName = shortName
    self.distillery = distillery

}


init(snapshot: FIRDataSnapshot) {
    key = snapshot.key
    ref = snapshot.ref
    let snapshotValue = snapshot.value as! [String: AnyObject]
    favourite = snapshotValue["favourite"] as? Bool
    currentUserID = snapshotValue["currentUserID"] as? String
    realIndex = snapshotValue["realIndex"] as? Int
    shortName = snapshotValue["shortName"] as? String
    distillery = snapshotValue["distillery"] as? String
}
func toAnyObject() -> Any {
    return [
        "favourite": favourite as Any,
        "currentUserID": currentUserID as Any,
        "realIndex": realIndex as Any,
        "shortName": shortName as Any,
        "distillery": distillery as Any,
    ]
}

到目前为止,我使用它的唯一方法就是使用在线curl-to-PHP转换器对我的查询进行硬编码:

{
  "query": [
    {
      "code": "series1",
      "selection": {
        "filter": "item",
        "values": [
          "1",
          "2",
          "3"
        ]
      }
    },
    {
      "code": "series2",
      "selection": {
        "filter": "item",
        "values": [
          "1",
          "2",
          "3"
        ]
      }
    }
  ],
  "response": {
    "format": "json"
  }
}

是否有更好的方法以更易读的格式将查询存储为变量,并将此变量传递给curl_setopt?

1 个答案:

答案 0 :(得分:1)

使用array和json-encode:

$data = ["query" => "...", "response" => ["format" => "json"]];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

upd。:您可以尝试这个简单的解决方案

function curl(string $method, string $url, array $data = [])
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    if ('POST' === $method) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

然后:

curl('POST', 'http://myApi/foo/bar', ['a' => 'b']);