PHP
For Laravel projects, see the public UnifyUnits Laravel client repository. The examples below use PHP cURL directly.
Single conversion
php
<?php
$url = 'https://api.unifyunits.com/v1/convert?value=1&from=ft&to=m';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('UNIFYUNITS_API_KEY'),
],
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status < 200 || $status >= 300) {
$error = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
throw new RuntimeException($error['error']['code'] . ': ' . $error['error']['message']);
}
$data = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
echo $data['data']['result']['value']; // "0.3048"Batch conversion
php
<?php
$payload = json_encode([
'conversions' => [
['value' => '10', 'from' => 'kg', 'to' => 'lb'],
['value' => '100', 'from' => 'km', 'to' => 'mi'],
],
]);
$ch = curl_init('https://api.unifyunits.com/v1/batch');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('UNIFYUNITS_API_KEY'),
'Content-Type: application/json',
],
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
foreach ($result['data'] as $item) {
if ($item['status'] === 'success') {
echo "Item {$item['index']}: {$item['result']['value']} {$item['result']['unit']}\n";
} else {
echo "Item {$item['index']} failed: {$item['error']['code']}\n";
}
}