PHP
Public
cURL GET Request in PHP
Call an external API with cURL and decode the JSON response.
#php
#curl
#api
#json
PHP
<?php
$ch = curl_init('https://api.example.com/items');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$responseBody = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($responseBody === false || $statusCode >= 400) {
throw new RuntimeException('API request failed: ' . $error);
}
$data = json_decode($responseBody, true);
Notes
In production, handle timeouts and log failed external API calls.