在PHP转换中使用curl的PUT请求

时间:2018-07-18 20:15:08

标签: php json api curl

我必须用PHP发出PUT请求,在API文档中,我有一个示例:

 curl --request PUT \
      --url 'http://url
      --header 'Content-Type: application/json' \
      --header 'TOKENMM: {{TOKEN}}' \
      --data '[
    {
    "item1": 123,
    "item2": 231,
    "item3": 321
    },
  {
    "item1": 456,
    "item2": 465,
    "item3": 654
  }
]'

如何使用PHP的curl发出该请求?我尝试了类似问题的一些答案,但没有成功。

这是我到目前为止所拥有的:

private function getInfoAPI($data_json){

        print_r($data_json);
        $url = 'url';
        $authorization = "TOKENMM: token";

    $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,  ['Content-Type: application/json', $authorization]);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response  = curl_exec($ch);
        echo curl_error($ch);
        var_dump( curl_getinfo ( $ch ) );
        curl_close($ch);

        return $response;
    }

1 个答案:

答案 0 :(得分:0)

我通过在Postman上构建请求并在PHP中生成代码来解决了这个问题。对我有用的代码是:

private function getInfoAPI($data_json){

        $curl = curl_init();
        curl_setopt_array($curl, [CURLOPT_URL => "url",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "PUT",
        CURLOPT_POSTFIELDS => $data_json,
        CURLOPT_HTTPHEADER => [
        "Cache-Control: no-cache",
        "Content-Type: application/json",
        "TOKEN: SAMPLE_TOKEN"],]);

        $response = curl_exec($curl);    
        curl_close($curl);

        return $response;
    }