2015-09-08 116 views
0

我有一个JSON阵列与雅虎天气API数据:转换JSON字符串PHP变量

"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" 
     } 
     } 
    } 
    } 
} 

我只需要得到temptext,并保存为变量......我该怎么办呢?

我试过编码,解码,subtr和其他一些方法,但似乎无法得到正确的语法。从Convert JSON string to PHP Array

这里 我试图说明是在我的网站代码:

$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; 
+0

我试过的建议那个链接(echo $ json-> temp;)但它没有回应任何东西 –

+0

当你console.log($ json)时你会得到什么? –

+0

未捕获的ReferenceError:$ json没有被定义(...) 我没有使用JavaScript的所有这一点,只有php –

回答

2

首先一个json_decode()的结果应该是一个对象或数组所以要查看它不使用echo尝试使用print_r()var_dump()

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

要获得2个值你有兴趣在您的数据中的所有数据结构对象使用: -

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

如果不能确保json_decode()工作,可能被严重形成的JSON字符串然后测试json_decode()像这样的错误的结果: -

$phpObj = json_decode($json); 
if (json_last_error() !== 0) { 
    echo json_last_error_msg(); 
} else { 
    print_r($phpObj); 
} 
+0

我试着你放,但没有任何回应。当我运行第二部分时没有错误,只返回字符串: stdClass Object [[query] => stdClass Object([count] => 1 [created] => 2015-09-08T16:05:36Z [lang] => stdClass对象([条件] => stdClass对象([条件] => stdClass对象([条件] => stdClass对象([通道] => stdClass对象08 Sep 2015 11:34 am EDT [temp] => 82 [text] =>轻微细雨)))))) –

+0

JK我明白了!我只是不得不添加条件!很高兴我现在知道语法!非常感谢! –