PHP Examples
These examples use PHP's built-in curl extension (PHP 7.4+).
Helper Function
Reuse this function for all API calls:
<?php
function geocodeme_get(string $path, array $params = []): object {
$apiKey = getenv('GEOCODEME_API_KEY');
if (!$apiKey) {
throw new RuntimeException('Set the GEOCODEME_API_KEY environment variable');
}
// Strip control characters to prevent header injection
$apiKey = preg_replace('/[\x00-\x1f\x7f]/', '', $apiKey);
// Only allow URL-safe path characters
if (!preg_match('#^/[a-zA-Z0-9/_-]*$#', $path)) {
throw new InvalidArgumentException('Invalid API path');
}
$url = 'https://api.geocodeme.net/v1' . $path;
if ($params) {
$url .= '?' . http_build_query($params);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-Api-Key: " . $apiKey]);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$body = curl_exec($ch);
if ($body === false) {
$err = curl_error($ch);
curl_close($ch);
throw new RuntimeException("cURL error: $err");
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($body);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Invalid JSON response: ' . json_last_error_msg());
}
if ($httpCode !== 200) {
$code = $data->error->code ?? $httpCode;
$msg = $data->error->message ?? $body;
throw new RuntimeException("Error: {$code} — {$msg}");
}
return $data;
}
Forward Geocoding
<?php
$data = geocodeme_get('/geocode', ['q' => '1 rue de Rivoli, Paris', 'limit' => 1]);
$location = $data->results[0];
echo "{$location->lat}, {$location->lon}" . PHP_EOL;
Reverse Geocoding
<?php
// /v1/reverse returns a single `result` object (or null), not an array
$data = geocodeme_get('/reverse', ['lat' => 48.8566, 'lon' => 2.3522]);
if ($data->result !== null) {
echo $data->result->display_name . PHP_EOL;
}