zoukankan      html  css  js  c++  java
  • 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

    代码如下:

    <?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;
    
    }

    经过修改上面代码,可以完成提交数组的功能,而不会报php notice,代码如下:

    //通过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, http_build_query($data));    //所需传的数组用http_bulid_query()函数处理一下,就ok了
        
        //执行并获取url地址的内容
        $output = curl_exec($ch);
        $errorCode = curl_errno($ch);
        //释放curl句柄
        curl_close($ch);
        if(0 !== $errorCode) {
            return false;
        }
        return $output;
    
    }
  • 相关阅读:
    常量,基本运算符,if判断,while循环
    python解释器的垃圾回收机制,小整数池,变量的三个特性,is与==,与用户交互,数据类型的基本使用,基本运算符
    编程语言的分类,python解释器多版本共存.执行python的两种方式,变量,用户与程序交互
    编程简介
    bootstrap 无限极菜单
    JQuery lhgdialog使用
    mysql 不是主键不能删除的保护问题解决办法?
    遍历所有的选中的radio的个数和值
    MySQL 的 RowNum 实现
    Ibatis 测试出SQL
  • 原文地址:https://www.cnblogs.com/mingaixin/p/2763265.html
Copyright © 2011-2022 走看看