Start · Sprachen · PHP · Snippets · HTTP-Request mit cURL

HTTP-Request mit cURL

HTTP & Web

Ein GET-Request an eine JSON-API. Für produktiven Code besser Guzzle nutzen; für Skripte reicht cURL.

Code

<?php

declare(strict_types=1);

$ch = curl_init('https://api.github.com/repos/laravel/laravel');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_HTTPHEADER     => [
        'Accept: application/vnd.github+json',
        'User-Agent: programmierung.net',
    ],
]);

$response = curl_exec($ch);
$status   = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

if ($status !== 200) {
    throw new RuntimeException("HTTP $status");
}

$repo = json_decode($response, true, flags: JSON_THROW_ON_ERROR);
echo $repo['full_name'] . ' — ' . $repo['stargazers_count'] . ' Stars';
laravel/laravel — 79000 Stars