将 JSON 字符串转换为 PHP 变量

Tim*_*ott 2 php json encode decode

我有一个带有 Yahoo Weather API 数据的 JSON 数组:

"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"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

我尝试过编码、解码、subtr 和其他一些方法,但似乎无法获得正确的语法。我已经尝试过将 JSON 字符串转换为 PHP 数组的说明

这是我网站上的代码:

  $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;
Run Code Online (Sandbox Code Playgroud)

Rig*_*lly 6

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

$phpObj =  json_decode($json);
print_r($phpObj);
Run Code Online (Sandbox Code Playgroud)

要获得您感兴趣的 2 个值,因为数据中的所有数据结构都是对象,请使用:-

echo $phpObj->query->result->channel->item->temp;
echo $phpObj->query->result->channel->item->text;
Run Code Online (Sandbox Code Playgroud)

如果您不确定它json_decode()是否正常工作,则可能是 json 字符串格式不正确,然后测试结果json_decode()是否有任何错误,如下所示:-

$phpObj =  json_decode($json);
if ( json_last_error() !== 0 ) {
    echo json_last_error_msg();
} else {
    print_r($phpObj);
}
Run Code Online (Sandbox Code Playgroud)