PHP基于CURL发送JSON格式字符串的方法示例
本文实例讲述了PHP基于CURL发送JSON格式字符串的方法。分享给大家供大家参考,具体如下:
/*
*post发送JSON格式数据
*@param$urlstringURL
*@param$data_stringstring请求的具体内容
*@returnarray
*code状态码
*result返回结果
*/
functionpost_json_data($url,$data_string){
$ch=curl_init();
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
'Content-Type:application/json;charset=utf-8',
'Content-Length:'.strlen($data_string))
);
ob_start();
curl_exec($ch);
$return_content=ob_get_contents();
ob_end_clean();
$return_code=curl_getinfo($ch,CURLINFO_HTTP_CODE);
returnarray('code'=>$return_code,'result'=>$return_content);
}
$arr=array('a'=>'555','b'=>56454564);
dump(post_json_data('http://192.168.211.1/html/dump.php',json_encode($arr)));
注意:接收数据的时候不是用$_POST,而是
$content=file_get_contents('php://input');
PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线