3

I have a JSON array with Yahoo Weather API data:

"query":{
  "count":1,
  "created":"2015-09-08T15:33:25Z",
  "lang":"en-US",
  "results":{
    "channel":{
      "item":{
        "condition":{
          "code":"30",
          "date":"Tue, 08 Sep 2015 11:13 am EDT",
          "temp":"81",
          "text":"Partly Cloudy"
        }
      }
    }
  }
}

I just need to get temp and text and save them as variables... how do I do this?

I've tried encode, decode, subtr, and a few other methods, but can't seem to get the syntax right. I've tried instructions from Convert JSON string to PHP Array

Here's the code on my site:

  $BASE_URL = "http://query.yahooapis.com/v1/public/yql";
  $yql_query = 'select item.condition from weather.forecast  where woeid in (select woeid from geo.places(1) where text="'.$city.', '.$state.'")';
  $yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
  // Make call with cURL
  $session = curl_init($yql_query_url);
  curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
  $json = curl_exec($session);
  // Convert JSON to PHP object
  $phpObj =  json_decode($json);

    echo '<br><br><br><br>';

    echo $json;
3
  • I tried the suggestions in that link (echo $json->temp;) but it didn't echo anything Commented Sep 8, 2015 at 15:45
  • what do you get when you console.log($json) ? Commented Sep 8, 2015 at 15:48
  • Uncaught ReferenceError: $json is not defined(…) I'm not using javascript at all for this, only php Commented Sep 8, 2015 at 15:52

1 Answer 1

6

First the result of a json_decode() should be an object or an array so to view it dont use echo try using print_r() or var_dump()

$phpObj =  json_decode($json);
print_r($phpObj);

To get the 2 values you are interested in as all the data structures in your data are objects use :-

echo $phpObj->query->result->channel->item->temp;
echo $phpObj->query->result->channel->item->text;

If you are not sure that the json_decode() is working, possibly the json string is badly formed then test the result of the json_decode() for any errors like so :-

$phpObj =  json_decode($json);
if ( json_last_error() !== 0 ) {
    echo json_last_error_msg();
} else {
    print_r($phpObj);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried what you put, but nothing was echoed. no errors given when I ran the second section, only echoed the string: stdClass Object ( [query] => stdClass Object ( [count] => 1 [created] => 2015-09-08T16:05:36Z [lang] => en-US [results] => stdClass Object ( [channel] => stdClass Object ( [item] => stdClass Object ( [condition] => stdClass Object ( [code] => 9 [date] => Tue, 08 Sep 2015 11:34 am EDT [temp] => 82 [text] => Light Drizzle ) ) ) ) ) )
JK I got it! I just had to add condition too! So glad I know the syntax now! Thanks so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.