php使用curl扩展post多维数组问题

之前使用curl进行服务器接口请求,一般都是使用一维数组,代码如下:
<?php
$url = "http://www.test.com/"
$data = array('telnum'=>'1872972xxxx');
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS,$data);
$return = curl_exec ( $ch );
curl_close ( $ch );


由于业务需要 需要post一个多维数组过去 如果仅将上述$data参数修改为

$data = array(
    'data'=>array(
        'telnum' => '1872972xxxx',
        'username'=>'zhangxxxx',
        'pwd'=>'123456',
        'code'=>'6217'
    )
);


则会出现如下警告

Notice: Array to string conversion in /Users/zhangsheng/web/test.php on line 33

网上翻了翻 发现了解决办法  使用http_build_query()函数处理post参数

http_build_query 生成 URL-encode 之后的请求字符串

修改代码如下

<?php
$url = "http://www.test.com/"
$data = array(
    'data'=>array(
        'telnum' => '1872972xxxx',
        'username'=>'zhangxxxx',
        'pwd'=>'123456',
        'code'=>'6217'
    )
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS,http_build_query($data));
$return = curl_exec ( $ch );
curl_close ( $ch );


你可能感兴趣的:(curl)