php curl post json

php相关 / 2022年04月12日 11时07分 / 3017人浏览
PHP用CURL发送Content-type为application/json的POST请求方法
function json_post($url, $data = NULL,$data_type = 'json') {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if (!$data) {
        return 'data is null';
    }
    if (is_array($data)) {
        $data = json_encode($data);
    }
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Content-Length:' . strlen($data),
        'Cache-Control: no-cache',
        'Pragma: no-cache'
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($curl);
    $status = curl_getinfo($curl);
    curl_close($curl);
    if (isset($status['http_code']) && $status['http_code'] == 200) {
        if ($data_type == 'json') {
            $output = json_decode($res);
        }else{
             $output = $res;
        }
        return $output;
    } else {
      
        return FALSE;
    }

}