php post和get请求
1. POST请求
public function post($url, $params = array()) { /*初始化*/ $ch = curl_init(); /*设置变量*/ curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); /*执行并获取结果*/ $result = curl_exec($ch);
//将result 转成数组
$result = json_decode($result, true); /*释放cURL句柄*/ curl_close($ch); /*返回结果*/ return $result; }
2. GET请求(解说如上)
public function get($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); $result = curl_exec($ch);
$result = json_decode($result, true); curl_close($ch); return $result; }