-1

I'm using PHP to get a JSON response from a website and then process the response using json_decode. This is my PHP code:

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,"https://api.checkwx.com/taf/LLBG/?format=json");
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $headers = [
      'X-API-Key: 555555555'
  ];

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $response = curl_exec($ch);
  curl_close ($ch);
  $json=json_decode($response,true);
  $fulltaf = $json['status']['success']['data']['icao'];

This doesn't work.

This is the JSON data returned to be processed by json_decode:

{
    "status": "success",
    "data": [
        {
            "icao": "KPIE",
            "observed": "07-03-2017 @ 14:20Z",
            "raw_text": "KPIE 071353Z 13017G23KT 10SM CLR 21\/13 A3031 RMK AO2 SLP262 T02060128",
            "wind_degrees": 130,
        }
    ]
}
crashmstr
  • 28,043
  • 9
  • 61
  • 79
user4876846
  • 13
  • 1
  • 3

1 Answers1

0

You don't specify what didn't work?

First problem is that your JSON has a syntax error. I tried to validate your JSON using http://jsonlint.com and it flagged an extra comma after the 130 for wind_degrees. Check that actual response doesn't have that comma. The JSON won't parse properly with the extra comma.

The next problem is that data is an array (because its data is enclosed in brackets). In this example the array only has one element, [0], therefore to access icao you need to reference it as I show below.

My guess is that the following line didn't work correctly:

    $fulltaf = $json['status']['success']['data']['icao'];

Based on the JSON you listed, this line should be the following if you want to retrieve the icao member of data.

    $fulltaf = $json['data'][0]['icao'];

The following reference should return 'success' if you want to test for a successful response.

    $json['status']
HeatfanJohn
  • 7,143
  • 2
  • 35
  • 41