guzzlehttp/uri-template
RFC 6570 URI Template expansion for PHP. Build URLs by substituting variables into templates, handling reserved characters, query strings, and fragments. Lightweight Guzzle component installable via Composer, with tests and changelog included.
Install the package with composer require guzzlehttp/uri-template. Start by using the simple static API to expand URIs using RFC 6570 templates:
use GuzzleHttp\UriTemplate\UriTemplate;
$template = 'https://api.example.com/users{/id}{?filter*}';
$params = ['id' => 123, 'filter' => ['active' => true, 'role' => 'admin']];
echo UriTemplate::expand($template, $params);
// Outputs: https://api.example.com/users/123?active=true&role=admin
Check the README for basic usage and the RFC 6570 spec for template syntax (e.g., {/var}, {?key*}).
UriTemplate::expand() for one-off expansions.UriTemplate for repeated use (e.g., in service classes or SDKs):
$uriTemplate = new UriTemplate();
$url = $uriTemplate->expand('/users{/id}', ['id' => 42]);
* suffix: Leverage {'key*'} syntax to safely expand arrays and objects (e.g., {'query*'} => ['page' => 1, 'size' => 20]). Now handles empty nested arrays correctly (v1.0.6+).rawurlencode() for RFC 3986-compliant encoding. Reserved/fragment values now preserve existing percent-encoded triplets (v1.0.6+)./, ?, #) now correctly retain their leading characters even when defined variables expand to empty strings (e.g., {/id} with id => "" now yields / instead of omitting it entirely).%20) in variable values were not preserved. Fixed in v1.0.6—now retains original encoding.0 values expand correctly: Prior to v1.0.2, 0 used in arrays/objects would be skipped; now it expands as "0". Double-check if upgrading from older versions./, ?, or # will no longer be omitted if their associated variable expands to an empty string. For example, {/id} with id => "" now correctly produces / instead of being skipped.INF, -INF, NAN) on PHP 8.5+.?{list*} with list=[] yields ""). Use default values (e.g., ['list' => null]) if omission is desired./ vs ? prefix in templates carefully—{/var} affects the path; {?var} affects the query string.UriExpander service wrapper).var_dump(UriTemplate::expand(...)) with known inputs to validate expansions incrementally, especially for nested objects. Test with edge cases like empty arrays, percent-encoded values, or empty strings.is_finite($value)) to avoid unexpected behavior in older versions. v1.0.7 resolves this issue entirely.How can I help you explore Laravel packages today?