PHP 7.4 CURL 函数:使用 GET 方法获取并解码 JSON 数据
使用 PHP 7.4 CURL 函数获取并解码 JSON 数据
本文提供一个使用 PHP 7.4 编写的 CURL 函数,通过 GET 方法获取数据,并使用 json_decode 函数将 JSON 响应解码为 PHP 数组。
CURL 函数代码
function curlGet($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception('CURL Error: ' . $error);
}
curl_close($ch);
$decodedResponse = json_decode($response, true);
if ($decodedResponse === null) {
throw new Exception('Unable to decode JSON response');
}
return $decodedResponse;
}
使用示例
$url = 'http://example.com/api/data';
$response = curlGet($url);
// 使用返回的数组数据
foreach ($response as $item) {
echo $item['id'] . ': ' . $item['name'] . '\n';
}
注意
上述代码假设接口返回的是 JSON 数据,因此使用 json_decode 函数对返回的数据进行解码。如果接口返回的不是 JSON 数据,可以根据实际情况进行相应的解码。
原文地址: http://www.cveoy.top/t/topic/GBm 著作权归作者所有。请勿转载和采集!