<?php function sendPostRequest($url, $data) { // 初始化cURL $curl = curl_init(); // 设置cURL选项 curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 发起POST请求并获取响应 $response = curl_exec($curl); // 检查请求是否成功 if ($response === false) { // 处理请求失败的情况 $error = curl_error($curl); curl_close($curl); return "Error: " . $error; } // 关闭cURL资源 curl_close($curl); // 返回响应 return $response; } // 示例用法 $url = 'http://example.com/api'; $data = array( 'param1' => 'value1', 'param2' => 'value2' ); $response = sendPostRequest($url, $data); // 打印响应 echo $response; ?>
<?php function sendPostRequest($url, $data) { // 构建HTTP头信息 $options = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($data) ) ); // 创建上下文流 $context = stream_context_create($options); // 发起POST请求并获取响应 $response = file_get_contents($url, false, $context); // 返回响应 return $response; } // 示例用法 $url = 'http://example.com/api'; $data = array( 'param1' => 'value1', 'param2' => 'value2' ); $response = sendPostRequest($url, $data); // 打印响应 echo $response; ?>
<?php function sendGetRequest($url, $params) { // 将参数附加到URL $url = $url . '?' . http_build_query($params); // 发起GET请求并获取响应 $response = file_get_contents($url); // 返回响应 return $response; } // 示例用法 $url = 'http://example.com/api'; $params = array( 'param1' => 'value1', 'param2' => 'value2' ); $response = sendGetRequest($url, $params); // 打印响应 echo $response; ?>
标签:echo,http,url,优雅,响应,PHP,data,response From: https://www.cnblogs.com/xiondun/p/17565408.html