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;
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With