在PHP中,可以使用cURL庫或者file_get_contents()函數來發起GET請求。下面是兩種方法的示例:
<?php
function httpGet($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$url = "https://api.example.com/data";
$response = httpGet($url);
echo $response;
?>
<?php
function httpGet($url) {
$context = stream_context_create(['http'=>['method'=>'GET']]);
$response = file_get_contents($url, false, $context);
return $response;
}
$url = "https://api.example.com/data";
$response = httpGet($url);
echo $response;
?>
這兩個示例都會向指定的URL發起GET請求,并將響應內容輸出。你可以根據自己的需求選擇合適的方法。