php请求接口

来源:互联网 发布:切片软件哪个好 编辑:程序博客网 时间:2024/05/22 15:56

php模拟post发送请求,调用参数

方法:

function request_post($url = '', $param = '') {        if (empty($url) || empty($param)) {            return false;        }                $postUrl = $url;        $curlPost = $param;        $ch = curl_init();//初始化curl        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);        $data = curl_exec($ch);//运行curl        curl_close($ch);                return $data;    }
调用实例:

function testAction(){        $url = 'http://mobile.jschina.com.cn/jschina/register.php';        $post_data['appid']       = '10';        $post_data['appkey']      = 'cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ';        $post_data['member_name'] = 'zsjs123';        $post_data['password']    = '123456';        $post_data['email']    = 'zsjs123@126.com';        $o = "";        foreach ( $post_data as $k => $v )         {             $o.= "$k=" . urlencode( $v ). "&" ;        }        $post_data = substr($o,0,-1);        $res = $this->request_post($url, $post_data);               print_r($res);    }
php使用curl实现Get和Post请求的方法

1.cURL介绍

  cURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP、FTP、TELNET等

2.基本结构

  在学习更为复杂的功能之前,先来看一下在PHP中建立cURL请求的基本步骤:

  (1)初始化


    curl_init()

  (2)设置变量


    curl_setopt() 。最为重要,一切玄妙均在此。有一长串cURL参数可供设置,它们能指定URL请求的各个细节。要一次性全部看完并理解可能比较困难,所以今天我们只试一下那些更常用也更有用的选项。

  (3)执行并获取结果


    curl_exec()

  (4)释放cURL句柄


    curl_close()

3.cURL实现Get和Post


Get:

//初始化

$ch = curl_init();

  //设置选项,包括URL
  curl_setopt($ch, CURLOPT_URL, "http://www.jb51.net");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, 0);

  //执行并获取HTML文档内容
  $output = curl_exec($ch);

  //释放curl句柄
  curl_close($ch);

  //打印获得的数据
  print_r($output);


Post:

$url="";

$post_data= array('id'=> '1','name'=>'zhangsan');

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  // post数据
  curl_setopt($ch, CURLOPT_POST, 1);
  // post的变量
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

  $output = curl_exec($ch);
  curl_close($ch);

  //打印获得的数据
  print_r($output);



以上方式获取到的数据是json格式的,使用json_decode函数解释成数组。

$output_array = json_decode($output,true);

如果使用json_decode($output)解析的话,将会得到object类型的数据。





0 0
原创粉丝点击