php使用curl post josn数据

今天在工作中使用到要使用("Content-Type", "application/json;charset=UTF-8")格式传送和接受数据,再次做个记录

post数据方法

function request_post($url = '', $param = '' ,$tmp = '') {
    if (empty($url) || empty($param)) {
        return false;
    }
    $header = array();
	if(!empty($tmp))$header[] = 'Authorization:'.$tmp;
	$header[] = 'Accept:application/json';
	$header[] = "Content-Type: application/json";
    $postUrl = $url;
    $curlPost = json_encode($param);
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

下面是接收这类型数据的方法

$c = file_get_contents('php://input');
$arr = json_encode($c,true);

  

原文地址:https://www.cnblogs.com/echoou/p/9113556.html