How to send a GET request and retrieve data in PHP?

To send a GET request in PHP and retrieve the response data, you can use the following method:

$url = 'https://api.example.com/data'; // 设置要发送GET请求的URL

// 初始化cURL会话
$ch = curl_init();

// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $url); // 设置请求的URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 设置返回结果为字符串
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用SSL证书验证

// 执行cURL会话并获取返回数据
$response = curl_exec($ch);

// 检查是否有错误发生
if($response === false) {
    echo 'cURL error: ' . curl_error($ch);
} else {
    // 输出返回数据
    echo $response;
}

// 关闭cURL会话
curl_close($ch);

The code example above demonstrates sending a GET request using the cURL library and retrieving the returned data. It is important to ensure that the cURL extension is installed in PHP.

bannerAds