这是代码:
<?php
$userFriends = json_decode(file_get_contents("http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=[api-key]&steamid=[steam-id]&relationship=all"), true);
foreach ($userFriends->data as $friend) {
//$json = json_decode(file_get_contents("http://steamcommunity.com/market/priceoverview/?appid=730&market_hash_name=".rawurlencode($item)), true);
echo $friend->friends;
}
?>
无法解析。问题出在哪里?
首先,如果你想使用 oo ->
语法访问 JSON 数据,你必须从json_decode
中删除True
参数:
$userFriends = json_decode( file_get_contents( ... ), true );
然后,您的 JSON 具有以下结构:
{
"friendslist": {
"friends": [
{
"steamid": "0123456789",
"relationship": "friend",
"friend_since": 0
},
(...)
]
}
}
因此,要访问朋友,您必须编写以下内容:
foreach( $userFriends->friendslist->friends as $friend )
{
echo $friend->steamid . PHP_EOL;
echo $friend->relationship . PHP_EOL;
echo $friend->friend_since . PHP_EOL;
}
可以将其作为数组读取
<?php
$userFriends = json_decode(file_get_contents("http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=[api-key]&steamid=[steam-id]&relationship=all"), true);
foreach ($userFriends['friendslist']['friends'] as $friend) {
echo $friend['steamid'];
echo $friend['relationship'];
echo $friend['friend_since'];
}
?>
您可以使用它来获取最后一个 JSON 错误,以防万一。 当然,只需回显错误而不是使用我的确切代码。
switch (json_last_error()) {
case JSON_ERROR_NONE:
//echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
header($_SERVER["SERVER_PROTOCOL"].'500 Maximum stack depth exceeded');
$this->response = array('error' => 'JSON Decode error - Maximum stack depth exceeded');
return $this->return_response();
break;
case JSON_ERROR_STATE_MISMATCH:
header($_SERVER["SERVER_PROTOCOL"].'500 Underflow or the modes mismatch');
$this->response = array('error' => 'JSON Decode error - Underflow or the modes mismatch');
return $this->return_response();
break;
case JSON_ERROR_CTRL_CHAR:
header($_SERVER["SERVER_PROTOCOL"].'500 Unexpected control character found');
$this->response = array('error' => 'JSON Decode error - Unexpected control character found');
return $this->return_response();
break;
case JSON_ERROR_SYNTAX:
header($_SERVER["SERVER_PROTOCOL"].'500 Syntax error, malformed JSON');
$this->response = array('error' => 'JSON Decode error - Syntax error, malformed JSON');
return $this->return_response();
break;
case JSON_ERROR_UTF8:
header($_SERVER["SERVER_PROTOCOL"].'500 Malformed UTF-8 characters, possibly incorrectly encoded');
$this->response = array('error' => 'JSON Decode error - Malformed UTF-8 characters, possibly incorrectly encoded');
return $this->return_response();
break;
default:
header($_SERVER["SERVER_PROTOCOL"].'500 Unknown JSON Decode error');
$this->response = array('error' => 'JSON Decode error - Unknown error');
return $this->return_response();
break;
}