将 JSON 字符串转换为 PHP 变量
Convert JSON string to PHP Variable
我有一个包含 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"
}
}
}
}
}
我只需要获取 temp
和 text
并将它们保存为变量...我该怎么做?
我试过编码、解码、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;
首先,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);
}
我有一个包含 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"
}
}
}
}
}
我只需要获取 temp
和 text
并将它们保存为变量...我该怎么做?
我试过编码、解码、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;
首先,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);
}