先来看一下在PHP中建立curl请求的基本步骤:
(1)初始化
curl_init()
(2)设置变量
curl_setopt()。最为重要。有一长串curl参数可供设置,它们能指定URL请求的各个细节。要一次性全部看完并理解可能比较困难,所以今天我们只试一下那些更常用也更有用的选项。
(3)执行并获取结果
curl_exec()
(4)释放cURL句柄
curl_close()
下面就看一下具体的实现:
1、post方式实现(模拟post请求,调用接口)
<?php
$url = "http://www.dyp.com/index.php/addUser"; // 你要请求的地址
$postData = array(
"uid" => "111",
"username" => "dyp"
);
$ch = curl_init(); // 初始化curl
curl_setopt($ch, CURLOPT_URL, $url); // 抓取指定网页
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 要求结果为字符串并输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1); // post请求方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); // post变量
$output = curl_exec($ch); // 执行并获得HTML内容
curl_close($ch); // 释放curl句柄
print_r($output);
2、get方式实现
<?php
$url = "http://www.dyp.com/test/"; // 你要请求的地址
$ch = curl_init(); // 初始化crul
curl_setopt($ch, CURLOPT_URL, $url); // 抓取指定网页
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 要求结果为字符串并输出到屏幕上
curl_setopt($ch, CURLOPT_HEADER, 0); // 设置header
$output = curl_exec($ch); // 执行并获得HTML内容
curl_close($ch); // 释放curl句柄
print_r($output);