🌤️ الدرس 12 من 13
مشروع: تطبيق الطقس
API Requests و JSON في PHP
استدعاء APIs في PHP
PHP يمكنها التواصل مع APIs خارجية لجلب بيانات حقيقية. سنستخدم OpenWeatherMap API لجلب بيانات الطقس.
الأدوات المستخدمة:
للاستخدام الحقيقي: احصل على API key مجاني من openweathermap.org
الأدوات المستخدمة:
file_get_contents(): جلب URL بسيطcURL: طريقة متقدمة وأكثر تحكماًjson_decode(): تحويل JSON إلى PHP array/objectjson_encode(): تحويل PHP إلى JSON
للاستخدام الحقيقي: احصل على API key مجاني من openweathermap.org
PHP
<?php
function getWeather(string $city, string $apiKey): array {
$url = "https://api.openweathermap.org/data/2.5/weather"
. "?q=" . urlencode($city)
. "&appid=" . $apiKey
. "&units=metric"
. "&lang=ar";
// استخدام cURL للطلب
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200 || !$response) {
return ["error" => "فشل في جلب البيانات"];
}
$data = json_decode($response, true);
return [
"city" => $data["name"],
"country" => $data["sys"]["country"],
"temp" => round($data["main"]["temp"]),
"feels_like" => round($data["main"]["feels_like"]),
"humidity" => $data["main"]["humidity"],
"description" => $data["weather"][0]["description"],
"wind" => round($data["wind"]["speed"] * 3.6), // m/s to km/h
"icon" => $data["weather"][0]["icon"],
];
}
// استخدام الدالة
$apiKey = "YOUR_API_KEY_HERE";
$weather = getWeather("Cairo", $apiKey);
if (isset($weather["error"])) {
echo "❌ " . $weather["error"];
} else {
echo "🌍 {$weather['city']}, {$weather['country']}<br>";
echo "🌡️ {$weather['temp']}°C (يشعر بـ {$weather['feels_like']}°C)<br>";
echo "💧 الرطوبة: {$weather['humidity']}%<br>";
echo "💨 الرياح: {$weather['wind']} كم/ساعة<br>";
echo "☁️ {$weather['description']}<br>";
}
?>
الناتج المتوقع
🌍 Cairo, EG
🌡️ 28°C (يشعر بـ 30°C)
💧 الرطوبة: 45%
💨 الرياح: 18 كم/ساعة
☁️ صحو جزئياًالكود الكامل لتطبيق الطقس
تطبيق طقس كامل بواجهة جميلة يعمل مع أي مدينة في العالم.
ملاحظة مهمة: هذا الكود يحتاج API Key حقيقي. للتجربة بدون API، استبدل دالة getWeather بـ بيانات وهمية (Mock Data) كما في المثال.
ملاحظة مهمة: هذا الكود يحتاج API Key حقيقي. للتجربة بدون API، استبدل دالة getWeather بـ بيانات وهمية (Mock Data) كما في المثال.
PHP
<?php
// Mock data للتجربة (بدلاً من API حقيقي)
function getMockWeather(string $city): array {
$cities = [
"cairo" => ["temp"=>28,"humidity"=>45,"desc"=>"صحو جزئياً","wind"=>18,"emoji"=>"⛅"],
"riyadh" => ["temp"=>38,"humidity"=>20,"desc"=>"مشمس","wind"=>25,"emoji"=>"☀️"],
"dubai" => ["temp"=>35,"humidity"=>60,"desc"=>"حار ورطب","wind"=>15,"emoji"=>"🌤️"],
"london" => ["temp"=>12,"humidity"=>80,"desc"=>"غائم","wind"=>30,"emoji"=>"🌧️"],
];
$key = strtolower($city);
$data = $cities[$key] ?? ["temp"=>22,"humidity"=>55,"desc"=>"معتدل","wind"=>20,"emoji"=>"🌤️"];
return array_merge($data, ["city" => ucfirst($city)]);
}
$weather = null;
if ($_POST["city"] ?? false) {
$city = htmlspecialchars(trim($_POST["city"]));
$weather = getMockWeather($city);
}
?>
<!DOCTYPE html>
<html dir="rtl">
<head>
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { min-height:100vh; background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);
display:flex; align-items:center; justify-content:center; font-family:Arial; }
.app { background:rgba(255,255,255,.1); backdrop-filter:blur(20px);
border:1px solid rgba(255,255,255,.2); border-radius:24px;
padding:40px; width:380px; color:white; text-align:center; }
h1 { font-size:1.5rem; margin-bottom:24px; }
form { display:flex; gap:10px; margin-bottom:20px; }
input { flex:1; padding:12px; border:none; border-radius:10px;
background:rgba(255,255,255,.15); color:white; font-size:1rem; }
input::placeholder { color:rgba(255,255,255,.6); }
button { padding:12px 20px; background:#39ff14; color:#000; border:none;
border-radius:10px; font-weight:bold; cursor:pointer; }
.weather-card { background:rgba(255,255,255,.08); border-radius:16px; padding:24px; }
.emoji { font-size:4rem; margin:10px 0; }
.temp { font-size:3rem; font-weight:800; color:#39ff14; }
.info { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-top:16px; }
.info-item { background:rgba(255,255,255,.1); border-radius:10px; padding:10px; font-size:.85rem; }
.label { color:rgba(255,255,255,.6); font-size:.75rem; }
</style>
</head>
<body>
<div class="app">
<h1>🌤️ تطبيق الطقس</h1>
<form method="POST">
<input name="city" placeholder="أدخل اسم المدينة..." required>
<button>بحث</button>
</form>
<?php if ($weather): ?>
<div class="weather-card">
<div class="emoji"><?= $weather['emoji'] ?></div>
<h2><?= $weather['city'] ?></h2>
<div class="temp"><?= $weather['temp'] ?>°C</div>
<p><?= $weather['desc'] ?></p>
<div class="info">
<div class="info-item"><div class="label">الرطوبة</div><?= $weather['humidity'] ?>%</div>
<div class="info-item"><div class="label">الرياح</div><?= $weather['wind'] ?> كم/ساعة</div>
</div>
</div>
<?php endif; ?>
</div>
</body>
</html>
الناتج المتوقع
// تطبيق طقس جميل بواجهة Glassmorphism
// يدعم القاهرة، الرياض، دبي، لندن...🧠
اختبر فهمك — مشروع: تطبيق الطقس
5/5 للمتابعةالسؤال 1
ما دالة PHP لتحويل JSON string إلى PHP array؟
السؤال 2
ما الفرق بين file_get_contents() و cURL؟
السؤال 3
ما دالة PHP لتشفير النص ليكون آمناً في URL؟
السؤال 4
ما الـ HTTP status code الذي يعني "OK - الطلب نجح"؟
السؤال 5
ما وحدة سرعة الرياح التي يُرجعها OpenWeatherMap API افتراضياً؟