PHP使用Curl扩展Post多维数组的例子

http://www.moqifei.com/archives/1462
使用curl进行服务器请求接口数据,一般情况下都是post一维数组。
我写下例子.我们一般会这样写.

$data = array(
 'name'=>'qiuyumi'
);
$url = "http://www.05gzs.com/";
function curlPost($url,$data) {
 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch,CURLOPT_POSTFIELDS,$data); 
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $reponse = curl_exec($ch);
 if(curl_errno($ch)>0){
 return false;
 }
 curl_close($ch);
 return $reponse;
}
print_r(curlPost($url,$data));
/*
返回值:{"status":true,"available":true}
*/

2.curl post的数组可能是多维数组,如果我们直接传递会报错(Notice),那么php有一个内置函数,可以把数组生成一个queryString的函数.http_build_query();。所以以后传递数据的时候最好把使用http_build_query转换一下.特别是在写基础函数的时候一定要转换一下。

<?php
$data = array(
 'name_list'=> array('zhangsan','lisi','zhaoer'),
 'age_list'=>array('16','14','19'),
 'name'=>'person'
);
$url = "http://www.05gzs.com/";
function curlPost($url,$data) {
 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($data)); 
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $reponse = curl_exec($ch);
 if(curl_errno($ch)>0){
 return false;
 }
 curl_close($ch);
 return $reponse;
}
echo http_build_query($data);
// print_r(curlPost($url,$data));
转自:http://blog.chinaunix.net/uid-26729093-id-4702094.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值