← Back to Chapters

PHP Coronavirus API

? PHP Coronavirus API

? Quick Overview

The Coronavirus API allows developers to fetch real-time COVID-19 statistics such as confirmed cases, recoveries, and deaths. PHP can consume this API and display live global or country-wise data on a webpage.

? Key Concepts

  • REST API consumption using PHP
  • JSON data parsing with json_decode()
  • Fetching remote data using file_get_contents()
  • Displaying live health statistics

? Syntax / Theory

The API returns JSON data. PHP fetches the response, decodes it into an associative array, and accesses individual values like cases, deaths, and recoveries.

? Code Example: Global COVID-19 Data

? View Code Example
// Fetch global COVID-19 statistics from API
Global COVID-19 Stats";
echo "Cases: " . $data['cases'] . "
";
echo "Deaths: " . $data['deaths'] . "
";
echo "Recovered: " . $data['recovered'] . "
";
?>

? Code Example: Country Specific Data

? View Code Example
// Fetch COVID-19 statistics for a specific country
COVID-19 Stats for {$country}";
echo "Cases: " . $data['cases'] . "
";
echo "Today Cases: " . $data['todayCases'] . "
";
echo "Deaths: " . $data['deaths'] . "
";
echo "Recovered: " . $data['recovered'] . "
";
?>

? Sample API Response

? View Code Example
// Sample JSON response returned by the API
{
"cases":700000000,
"deaths":6900000,
"recovered":670000000,
"todayCases":1200,
"todayDeaths":50
}

? Live Output / Explanation

The API response is decoded into an array and individual statistics are printed dynamically. Data updates automatically whenever the API data changes.

? Interactive / Visual Idea

You can connect this API to charts or dashboards using JavaScript libraries like Chart.js to visualize trends with auto-refresh using AJAX.

? Use Cases

  • COVID-19 tracking dashboards
  • Health monitoring portals
  • Educational data analysis projects
  • Real-time statistics websites

✅ Tips & Best Practices

  • Always validate API responses before use
  • Implement caching to reduce API calls
  • Use cURL for better error handling in production

? Try It Yourself

  • Display multiple countries in a table
  • Add charts for daily cases
  • Build an auto-refresh COVID dashboard using AJAX