Want to add Coronavirus data to your website? It’s simple with PHP and JSON. There are numerous resources available to pull data from. For this example I will utilize the COVID Tracking Project API.
API Data
Visit the COVID Tracking Projects API page and find your State from the “States Current Values” option.
API URL Format
https://covidtracking.com/api/v1/states/STATEABBREVIATION/current.json
API URL Format Example (Virginia)
https://covidtracking.com/api/v1/states/VA/current.json
Test Your States API Link – the data returned should look simular to the following example;
{"state":"VA","positive":9952,"positiveScore":1,"negativeScore":1,"negativeRegularScore":1,"commercialScore":1,"grade":"A","score":4,"negative":50826,"pending":495,"hospitalizedCurrently":1374,"hospitalizedCumulative":1659,"inIcuCurrently":419,"inIcuCumulative":null,"onVentilatorCurrently":244,"onVentilatorCumulative":null,"recovered":1497,"lastUpdateEt":"4/22 00:00","checkTimeEt":"4/22 23:05","death":349,"hospitalized":1659,"total":61273,"totalTestResults":60778,"posNeg":60778,"fips":"51","dateModified":"2020-04-22T04:00:00Z","dateChecked":"2020-04-23T03:05:00Z","notes":"Please stop using the \"total\" field. Use \"totalTestResults\" instead.","hash":"d825dfd0831d0e270650be1f3ccd6a3758c5ade8"}
PHP Data
- Use cURL to make the request via your API URL determined above to get get the JSON data
- Note: You must have the cURL extension enabled in your PHP environment
- Use json_decode to decode the JSON data
- Assign variables to the decoded JSON dataset
- Print (echo) the variables
Complete PHP Example
<?php /* Sample Code Created by SullysRants.com */ // The COVID Tracking Project (https://covidtracking.com/api) $API_Data = "https://covidtracking.com/api/v1/states/VA/current.json"; // cURL Options $ch = curl_init($API_Data); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); $response = curl_exec($ch); // Decode the Response $result = json_decode($response); // Variables for Respone Data $Positive = $result->positive; $Negative = $result->negative; $Pending= $result->pending; $Hospital_Currently = $result->hospitalizedCurrently; $Hospital_Total = $result->hospitalized; $ICU_Currently = $result->inIcuCurrently; $Ventilator_Currenlty = $result->onVentilatorCurrently; $Recovered = $result->recovered; $Deaths = $result->death; $Updated = strtotime($result->dateModified); $Last_Updated = date("m/d/y - h:i", $Updated); // Display the Data echo "<p>Testing</p>"; echo "Positive: " .$Positive. "<br>"; echo "Negative: " .$Negative. "<br>"; echo "Pending: " .$Pending; echo "<p>Hospitalization</p>"; echo "Current Hospitalizations: " .$ICU_Currently. "<br>"; echo "Current In ICU: " .$Ventilator_Currenlty. "<br>"; echo "Current On Ventilator: " .$Ventilator_Currenlty. "<br>"; echo "Total Hospitalizations: " .$Hospital_Total. "<br>"; echo "<p>Recovery/Fatality</p>"; echo "Recovered: " .$Recovered. "<br>"; echo "Deaths: " .$Deaths; echo "<p>Updated</p>"; echo"Last Update: ".$Last_Updated; ?>