【问题标题】:Convert JSON string to PHP Variable将 JSON 字符串转换为 PHP 变量
【发布时间】:2015-09-08 15:39:17
【问题描述】:

我有一个带有 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"
        }
      }
    }
  }
}

我只需要获取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;

【问题讨论】:

  • 我尝试了该链接中的建议 (echo $json->temp;) 但它没有回显任何内容
  • console.log($json) 得到什么?
  • Uncaught ReferenceError: $json is not defined(...) 我根本没有使用 javascript,只有 php

标签: php json decode encode


【解决方案1】:

首先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);
}

【讨论】:

  • 我试过你放的东西,但没有任何回应。当我运行第二部分时没有给出错误,只回显了字符串: 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 2015 年 9 月美国东部时间上午 11:34 [温度] => 82 [文本] => 细雨) ) ) ) ) )
  • JK 我明白了!我也只需要添加条件!很高兴我现在知道语法了!非常感谢!
猜你喜欢
  • 2018-02-08
  • 2020-11-26
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 2014-09-05
  • 2012-05-21
  • 2013-05-14
  • 2010-09-30
相关资源
最近更新 更多