Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2002901
  • 博文数量: 433
  • 博客积分: 918
  • 博客等级: 准尉
  • 技术积分: 3218
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 18:21
个人简介

你是不是暗恋我,那就给我发个消息呀,让我知道o(∩∩)o

文章分类

全部博文(433)

分类: LINUX

2014-12-17 18:59:05


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

$data = array(
 'name'=>'qiuyumi'
);
$url = "";
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转换一下.特别是在写基础函数的时候一定要转换一下。


$data = array(
 'name_list'=> array('zhangsan','lisi','zhaoer'),
 'age_list'=>array('16','14','19'),
 'name'=>'person'
);
$url = "";
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));
阅读(10995) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~