PHP

Parse Link Header for Pagination

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Parse the standard HTTP Link header (RFC 5988) into a relation → URL map. Lets you follow rel="next" pagination in APIs like GitHub without manually building URLs.
PHP
Raw
<?php
function parseLinkHeader(string $linkHeader): array {
    $out = [];
    foreach (explode(',', $linkHeader) as $part) {
        if (!preg_match('/<([^>]+)>;\s*rel="?([^";]+)"?/', $part, $m)) continue;
        $out[$m[2]] = $m[1];
    }
    return $out;
}

// Example response header from GitHub:
$header = '<https://api.github.com/repos/foo/bar/issues?page=2>; rel="next", '
        . '<https://api.github.com/repos/foo/bar/issues?page=10>; rel="last"';
$rels = parseLinkHeader($header);
echo $rels['next'];   // https://api.github.com/.../issues?page=2
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.