0

I'm using this link to obtain Air Quality data from an API https://api-ninjas.com/api/airquality

I want to do this via PHP due to it being a requirement

I have my PHP file

<?php

// Display errors is set to on and should be removed for production
    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

// Timing script execution
    $executionStartTime = microtime(true);


    $url='https://api.api-ninjas.com/v1/airquality?city=' . $_REQUEST['countryName'];
// Curl object is initiated
    $ch = curl_init();
    
//Curl_setopt() takes three parameters(Curl instance to use, setting you want to change, value you want to use for that setting)    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);

    $result=curl_exec($ch);

    curl_close($ch);

    $decode = json_decode($result, true);   

    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
    $output['result'] = $decode['result'];

    
    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output); 

?>

and then my JavaScript Function

function getAirQuality(countryName) {
    $.ajax({
        method: 'GET',
        url: "assets/php/getAirQuality.php",
        data: {
               countryName: countryName
                },
        headers: {
            'X-Api-Key': 'API_KEY'
        },
        contentType: 'application/json',
        success: function(result) {
            console.log(result);

            $('#aqCO').html(result['CO']['concentration'] + ' ppm');
            $('#aqSO').html(result['SO2']['concentration'] + ' ppm');
            $('#aqO3').html(result['O3']['concentration'] + ' g/m3');
            $('#aqNO2').html(result['NO2']['concentration'] + ' ppm');
            $('#aqPM2').html(result['PM2.5']['concentration'] + ' µg/m3');
            $('#aqPM10').html(result['PM10']['concentration'] + ' µg/m3');
        },

        error: function ajaxError(jqXHR) {
            console.error('Error: ', jqXHR.responseText);
        }
    });
}

However, the PHP file keeps complaining in the console Error: <br /> <b>Warning</b>: Undefined array key "result" in <b>C:\xampp1\htdocs\project1\assets\php\getAirQuality.php</b> on line <b>30</b><br /> {"status":{"code":"200","name":"ok","description":"success","returnedIn":"293 ms"},"result":null}

As you can see from the above website, the result should be like so

{
  "CO": {
    "concentration": 223.64,
    "aqi": 2
  },
  "NO2": {
    "concentration": 9.08,
    "aqi": 11
  },
  "O3": {
    "concentration": 26.46,
    "aqi": 22
  },
  "SO2": {
    "concentration": 0.78,
    "aqi": 1
  },
  "PM2.5": {
    "concentration": 4.04,
    "aqi": 13
  },
  "PM10": {
    "concentration": 6.23,
    "aqi": 5
  },
  "overall_aqi": 22
}

I'm not sure what else it could be? I've tried result, results and data

UPDATE So whilst I've got the data decoded fine

result
: 
CO
: 
{concentration: 223.64, aqi: 2}
NO2
: 
{concentration: 19.71, aqi: 24}
O3
: 
{concentration: 52.93, aqi: 44}
PM2.5
: 
{concentration: 11.67, aqi: 37}
PM10
: 
{concentration: 14.61, aqi: 13}
SO2
: 
{concentration: 1.97, aqi: 2}
overall_aqi
: 
44

I am trying to assign them to variable like so: $('#aqCO').html(result['CO']['concentration'] + ' ppm'); but it is returning Uncaught TypeError: Cannot read properties of undefined (reading 'concentration')

6
  • do a var_export( $decode) to see the data, but i guess you should use just a $decode, this api response doesn't have a data or a result or whatever keyword Commented Nov 2, 2022 at 19:38
  • @soma oh, turns out the var_export( $decode) is returning "Missing API Key." which is strange as I am passing it via my JavaScript function as per the websites suggestion Commented Nov 2, 2022 at 19:43
  • 2
    @hubbabubba438481 you have to pass the API key via PHP if you are calling the API via PHP. Commented Nov 2, 2022 at 19:44
  • I'm not sure how to pass it that it will be recognised in the PHP? I don;t know if its part of the URL or what Commented Nov 2, 2022 at 19:45
  • 1
    The API key is being used to authenticate your request between your server (PHP) and theirs, not between your end user (Javascript) and your server (PHP). Commented Nov 2, 2022 at 19:46

1 Answer 1

1

You can pass headers by creating an array and passing it via: CURLOPT_HTTPHEADER

$headers = ['X-Api-Key: API_KEY'];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
Sign up to request clarification or add additional context in comments.

7 Comments

This is still providing me with the error 'error' => 'Missing API Key.' :(
got it, curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'X-Api-Key: 000000', )); works much better
@hubbabubba438481 you are correct, I updated my answer. I forgot the array had to include the key and value in each element
However, whilst the data is being retrieved fine, I still can't get it to assign to my HTML variables
@hubbabubba438481 you are passing the data to the element "result" in your JSON output. So in your javascript you would use result["result"]["CO"] for example.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.