Convert JSON string to PHP Variable

10,025

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);
}
Share:
10,025
Timothy Richard Elliott
Author by

Timothy Richard Elliott

Updated on June 04, 2022

Comments

  • Timothy Richard Elliott
    Timothy Richard Elliott almost 2 years

    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;
    
  • Timothy Richard Elliott
    Timothy Richard Elliott over 8 years
    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 ) ) ) ) ) )
  • Timothy Richard Elliott
    Timothy Richard Elliott over 8 years
    JK I got it! I just had to add condition too! So glad I know the syntax now! Thanks so much!