php curl模拟post多维数组提交
用curl模拟post提交参数,请求同事提供的一个接口;
但是传递的参数中,有一个参数的值为数组,用普通的curl post代码提交,会报错误:
PHP Notice: Array to string conversion in /test/functions.php on line 30
Notice: Array to string conversion in /test/functions.php on line 30
代码1:
<?php
$param = array(
'uid' => 123,
'uids' => array(12,455),
'msgType' => 'WITH',
'nick' => 'aaa',
);
$url = "http://cx.com/t.php";
//通过curl的post方式发送接口请求
SendDataByCurl($url,$param);
//通过curl模拟post的请求;
function SendDataByCurl($url,$data=array()){
//对空格进行转义
$url = str_replace(' ','+',$url);
$ch = curl_init();
//设置选项,包括URL
curl_setopt($ch, CURLOPT_URL, "$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟
// POST数据
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//执行并获取url地址的内容
$output = curl_exec($ch);
//释放curl句柄
curl_close($ch);
return $output;
}
修正后的代码为: