PHP可以使用curl或file_get_contents函数发送HTTP请求数据。
- 使用curl发送HTTP请求数据:
a. 初始化curl:$ch = curl_init();
b. 设置curl选项:
- 设置请求的URL:curl_setopt($ch, CURLOPT_URL, $url);
- 设置请求方式为POST:curl_setopt($ch, CURLOPT_POST, true);
- 设置请求的数据:curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- 设置返回结果不直接输出:curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
c. 执行curl请求:$result = curl_exec($ch);
d. 关闭curl:curl_close($ch);
- 使用file_get_contents发送HTTP请求数据:
a. 构造请求数据:$data = array("key1" => "value1", "key2" => "value2");
b. 构造请求选项:$options = array("http" => array("method" => "POST", "header" => "Content-type: application/x-www-form-urlencoded", "content" => http_build_query($data)));
c. 发送HTTP请求并获取结果:$result = file_get_contents($url, false, stream_context_create($options));