PHP SDK
Geocoding from PHP with typed results, Composer autoloading, and optional backups.
The PHP SDK provides a synchronous client with normalized results and optional Google/HERE fallbacks. All classes use the AffordableGeoApis namespace.
Installation
Requires PHP 8.2+ with cURL and JSON extensions. No third-party runtime packages are required.
The package is not yet published. To use it from the repository:
cd sdk/php
composer install
Load sdk/php/vendor/autoload.php, or use the included sdk/php/autoload.php without Composer. For a separate Composer application, add a path repository:
{
"repositories": [
{
"type": "path",
"url": "/path/to/pelias/sdk/php",
"options": {"versions": {"affordable-geo-apis/sdk": "0.1.0"}}
}
],
"require": {"affordable-geo-apis/sdk": "0.1.0"}
}
Run composer update affordable-geo-apis/sdk, then load your application's vendor/autoload.php.
Quick start
Run this example from the repository root, or change the autoloader path for your application:
<?php
require 'sdk/php/autoload.php';
use AffordableGeoApis\GeocodingClient;
$client = new GeocodingClient([
'baseUrl' => getenv('GEOCODING_BASE_URL'),
'apiKey' => getenv('GEOCODING_API_KEY'),
]);
$response = $client->geocode([
'street' => '11 Wall Street',
'city' => 'New York',
'state' => 'NY',
'zip' => '10005',
]);
echo json_encode($response, JSON_THROW_ON_ERROR);
A no-match request succeeds with an empty $response->results array. Results expose readonly properties and implement JsonSerializable.
Authentication
Set your primary URL and API key:
export GEOCODING_BASE_URL='http://localhost:8000'
export GEOCODING_API_KEY='YOUR_API_KEY'
Pass them as baseUrl and apiKey. The SDK adds the apikey header. Use your assigned HTTPS URL in production, without the endpoint path.
Available methods
| Method | Use |
|---|---|
$client->geocode($request, $options = []) | Find coordinates for an address |
$client->search($request, $options = []) | Find addresses and places from one line of free text |
$client->reverseGeocode($request, $options = []) | Find address candidates for coordinates |
$client->autocomplete($request, $options = []) | Suggest addresses for partial text and a required country |
$client->resolveAutocomplete($suggestion, $options = []) | Resolve the selected suggestion into one address |
Geocode, search, and reverse geocode return GeocodingResponse. Autocomplete returns AutocompleteResponse; resolution returns GeocodingResult. See the client reference for options and model properties.
Common operations
Free-text search
$response = $client->search([
'q' => '11 Wall Street, New York, NY',
'country' => 'US',
'limit' => 5,
]);
Search accepts one line of text, such as an address, place name, city, or ZIP code, and returns matches of any type. q is required (1 to 256 bytes). country restricts results, near (['lat' => ..., 'lon' => ...]) prefers nearby results, and limit is 1 to 40 (default 10). Use geocode when the address is already split into fields. See search.
Address autocomplete
$response = $client->autocomplete(['q' => '11 Wall', 'country' => 'US', 'limit' => 5]);
if ($response->suggestions !== []) {
$address = $client->resolveAutocomplete($response->suggestions[0]);
echo $address->label;
}
Keep the suggestion object unchanged until selection. Resolution calls only its provider and does not run fallback selection or use fallback budgets/circuits. See autocomplete.
Reverse geocoding
$response = $client->reverseGeocode([
'lat' => 40.7074,
'lon' => -74.0113,
]);
Reading results
foreach ($response->results as $result) {
echo $result->label . ': ' . $result->lat . ', ' . $result->lon;
}
Use toArray() or json_encode() to serialize responses, nested results, attempts, and errors.
Configuration
Provider fallbacks
$client = new GeocodingClient([
'baseUrl' => getenv('GEOCODING_BASE_URL'),
'apiKey' => getenv('GEOCODING_API_KEY'),
'fallbackBudget' => ['maxRequests' => 1000],
'fallbacks' => [
['provider' => 'google', 'apiKey' => getenv('GOOGLE_MAPS_API_KEY')],
['provider' => 'here', 'apiKey' => getenv('HERE_API_KEY')],
],
]);
Backups run in order on no results, low confidence, or eligible primary outages. They are off by default. A request with 'country' => 'GB' skips primary and uses backups. See fallback policy.
Error handling
use AffordableGeoApis\GeocodingError;
try {
$response = $client->geocode(['street' => '11 Wall Street', 'city' => 'New York']);
} catch (GeocodingError $error) {
echo $error->errorCode;
echo $error->getMessage();
echo json_encode($error, JSON_THROW_ON_ERROR);
}
Use errorCode for the SDK's string code. PHP's inherited getCode() is numeric. Terminal provider errors include the attempt history; primary HTTP 4xx and malformed responses do not trigger backups.
Timeouts and cancellation
Constructor timeoutMs defaults to 10000 milliseconds per provider. Per-call timeoutMs bounds the whole chain:
$response = $client->geocode(
['street' => '11 Wall Street', 'city' => 'New York'],
['timeoutMs' => 15000],
);
Total deadline expiry throws RequestTimeoutException. A provider timeout is a GeocodingError and can trigger fallback. For cancellation, pass a CancellationToken in the per-call signal; cancellation throws RequestCancelledException.
Retries
The SDK does not retry automatically. Bound application retries and use backoff. Each call can consume primary and backup usage.
Raw provider response
if ($response->provider !== 'primary') {
echo json_encode($response->providerResponse, JSON_THROW_ON_ERROR);
}
The selected Google/HERE body is preserved as a stdClass. It is null for primary results and omitted during serialization.
Reuse a client to share fallback budgets and circuits. A new client resets them, including when created for each incoming PHP request. No close method is required.
For partial address entry, see address autocomplete.