在PHP POST上发送复杂的json数据

时间:2019-02-19 18:59:07

标签: php curl

我需要调用包含复杂主体数据的post方法:

{
    "client": {
      "clientId":      "yourcompanyname",
      "clientVersion": "1.5.2"
    },
    "threatInfo": {
      "threatTypes":      ["MALWARE", "SOCIAL_ENGINEERING"],
      "platformTypes":    ["WINDOWS"],
      "threatEntryTypes": ["URL"],
      "threatEntries": [
        {"url": "http://www.urltocheck1.org/"},
        {"url": "http://www.urltocheck2.org/"},
        {"url": "http://www.urltocheck3.com/"}
      ]
    }
  }

我发现了使用curlstream_context_create的不同示例,但是所有示例都只是使用数组作为正文数据。在我的示例中,没有人需要复杂的json结构。如何实现?

1 个答案:

答案 0 :(得分:1)

尝试:

$ch=curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data) );
curl_setopt($ch, CURLOPT_POST, true);
// not necessarily but ... 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload))
);

$result = curl_exec($ch);
curl_close($ch);