php curl json mysql_php 通过curl post发送json数据实例

利用php curl发送json数据与curl post其它数据是一样的,下面我来给大家总结几个关于curl post发送json数据实例,希望能加深各位对curl post json数据的理解吧。

例1

 代码如下复制代码

$data = array("name" => "Hagrid", "age" => "36");

$data_string = json_encode($data);

$ch = curl_init('http://api.local/rest/users');

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(

'Content-Type: application/json',

'Content-Length: ' . strlen($data_string))

);

$result = curl_exec($ch);

例2

 代码如下复制代码

function http_post_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);

return array($return_code, $return_content);

}

$url  = "http://xx.xx.cn";

$data = json_encode(array('a'=>1, 'b'=>2));

list($return_code, $return_content) = http_post_data($url, $data);

例3

 代码如下复制代码

$data=' {

"button":[

{

"type":"click",

"name":"今日歌曲",

"key":"V1001_TODAY_MUSIC"

},

{

"type":"click",

"name":"歌手简介",

"key":"V1001_TODAY_SINGER"

},

{

"name":"菜单",

"sub_button":[

{

"type":"click",

"name":"hello word",

"key":"V1001_HELLO_WORLD"

},

{

"type":"click",

"name":"赞一下我们",

"key":"V1001_GOOD"

}]

}]

}';

$ch = curl_init($urlcon); //请求的URL地址

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//$data JSON类型字符串

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));

$data = curl_exec($ch);

print_r($data);//创建成功返回:{"errcode":0,"errmsg":"ok"}

小结,我们发现最核心的一句代码就是Content-Type: application/json;这个是文件格式类型了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值