PHP WeatherAPI Integration with cURL: Complete Developer Guide
PHP remains one of the most popular server-side languages, powering millions of web applications worldwide. If you’re building a PHP application that needs reliable weather data, WeatherAPI offers a straightforward REST API that integrates seamlessly with PHP’s built-in cURL functions.
This tutorial walks through implementing WeatherAPI in PHP using cURL, covering authentication, data fetching, and robust error handling patterns that you can use in production applications.
Getting Started with WeatherAPI
WeatherAPI provides real-time weather data, forecasts, and historical information for over 4 million locations worldwide. With the free plan offering 100,000 API calls per month and no credit card required, it’s perfect for development and small to medium applications.
First, sign up for your free API key at WeatherAPI.com. You’ll use this key to authenticate all your requests.
Basic cURL Setup for WeatherAPI
Let’s start with a basic PHP class that handles WeatherAPI requests using cURL:
<?php
class WeatherAPI {
private $apiKey;
private $baseUrl = 'https://api.weatherapi.com/v1';
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
private function makeRequest($endpoint, $params = []) {
// Add API key to parameters
$params['key'] = $this->apiKey;
// Build URL with query parameters
$url = $this->baseUrl . $endpoint . '?' . http_build_query($params);
// Initialize cURL
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_USERAGENT => 'PHP WeatherAPI Client/1.0'
]);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = curl_error($curl);
curl_close($curl);
if ($error) {
throw new Exception("cURL Error: " . $error);
}
return $this->handleResponse($response, $httpCode);
}
}
Implementing Error Handling
Robust error handling is crucial for production applications. WeatherAPI returns specific HTTP status codes and error messages that help you handle different failure scenarios:
private function handleResponse($response, $httpCode) {
$data = json_decode($response, true);
if ($httpCode !== 200) {
$errorMessage = 'HTTP Error ' . $httpCode;
if (isset($data['error']['message'])) {
$errorMessage .= ': ' . $data['error']['message'];
}
switch ($httpCode) {
case 400:
throw new InvalidArgumentException($errorMessage);
case 401:
throw new UnauthorizedAccessException($errorMessage);
case 403:
throw new ForbiddenAccessException($errorMessage);
case 429:
throw new RateLimitException($errorMessage);
default:
throw new Exception($errorMessage);
}
}
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Invalid JSON response: ' . json_last_error_msg());
}
return $data;
}
Fetching Current Weather Data
Now let’s implement methods to fetch different types of weather data. The current weather endpoint provides real-time conditions including temperature, humidity, wind, and air quality:
public function getCurrentWeather($location) {
return $this->makeRequest('/current.json', [
'q' => $location,
'aqi' => 'yes' // Include air quality data
]);
}
public function getForecast($location, $days = 3) {
if ($days < 1 || $days > 14) {
throw new InvalidArgumentException('Days must be between 1 and 14');
}
return $this->makeRequest('/forecast.json', [
'q' => $location,
'days' => $days,
'aqi' => 'yes',
'alerts' => 'yes'
]);
}
public function getHistoricalWeather($location, $date) {
return $this->makeRequest('/history.json', [
'q' => $location,
'dt' => $date // Format: YYYY-MM-DD
]);
}
Practical Usage Examples
Here’s how to use the WeatherAPI class in your applications:
<?php
try {
$weather = new WeatherAPI('YOUR_API_KEY');
// Get current weather
$current = $weather->getCurrentWeather('London');
echo "Temperature in London: " . $current['current']['temp_c'] . "°C\n";
echo "Condition: " . $current['current']['condition']['text'] . "\n";
// Get 7-day forecast
$forecast = $weather->getForecast('New York', 7);
foreach ($forecast['forecast']['forecastday'] as $day) {
echo $day['date'] . ": " . $day['day']['maxtemp_c'] . "°C / " .
$day['day']['mintemp_c'] . "°C - " .
$day['day']['condition']['text'] . "\n";
}
// Auto-detect location from IP
$local = $weather->getCurrentWeather('auto:ip');
echo "Local weather: " . $local['current']['temp_c'] . "°C\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Advanced Features and Optimization
For production applications, consider implementing response caching to reduce API calls and improve performance:
private function getCachedResponse($cacheKey, $ttl = 600) {
// Implement your preferred caching mechanism
// Redis, Memcached, file cache, etc.
if ($cachedData = $this->cache->get($cacheKey)) {
return json_decode($cachedData, true);
}
return null;
}
public function getCurrentWeatherCached($location) {
$cacheKey = 'weather_current_' . md5($location);
if ($cached = $this->getCachedResponse($cacheKey)) {
return $cached;
}
$data = $this->getCurrentWeather($location);
$this->cache->set($cacheKey, json_encode($data), 600); // 10 min cache
return $data;
}
Next Steps
This PHP integration provides a solid foundation for weather data in your applications. WeatherAPI offers additional endpoints for marine data, astronomy information, and sports events that you can integrate using the same patterns.
Ready to start building? Get your free API key and begin integrating reliable weather data into your PHP applications today. With 100,000 free monthly calls, you can build and test your application without any upfront costs.
